# views.py
from django.contrib.messages.storage import default_storage
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Sum, Count, F
from decimal import Decimal
from datetime import timedelta
from django.utils import timezone
from .models import CartItem, User, Product, Order, OrderDetail, Category
from .address_models import Address
import json
import random
import re

@csrf_exempt
def search_all(request):
    if request.method == 'POST':
        try:
            # 解析请求数据
            data = json.loads(request.body)
            page = data.get('page', 1)
            page_size = data.get('pageSize', 10)
            keyword = data.get('keyword', '')
            category_id = data.get('categoryId')
            brand_id = data.get('brandId')
            
            sort_field = data.get('sortField', 'publishTime')
            sort_method = data.get('sortMethod', 'desc')

            # 构建基础查询
            products = Product.objects.all()

            # 关键词搜索
            if keyword:
                products = products.filter(name__icontains=keyword)

            # 分类筛选
            if category_id:
                products = products.filter(category_id=category_id)

            # 品牌筛选
            if brand_id:
                products = products.filter(brand_id=brand_id)

            # 特惠商品筛选
            

            # 排序处理
            sort_prefix = '-' if sort_method == 'desc' else ''
            if sort_field == 'publishTime':
                products = products.order_by(f'{sort_prefix}created_at')
            elif sort_field == 'orderNum':
                products = products.order_by(f'{sort_prefix}sales_count')
            elif sort_field == 'price':
                products = products.order_by(f'{sort_prefix}price')
            elif sort_field == 'evaluateNum':
                products = products.order_by(f'{sort_prefix}review_count')

            # 计算分页
            total_count = products.count()
            total_pages = (total_count + page_size - 1) // page_size
            start = (page - 1) * page_size
            end = start + page_size
            paginated_products = products[start:end]

            # 获取所有分类
            categories = Category.objects.all()[:8]
            categories_data = [{
                'id': str(category.id),
                'name': category.name
            } for category in categories]

            # 构建商品列表
            items = [{
                'id': str(product.id),
                'picture': f'/{product.image.name}' if product.image else '',
                'name': product.name,
                'price': float(product.price),
                'desc': product.description[:50] if product.description else '',
                'discount': 1.0
            } for product in paginated_products]

            # 构建返回数据
            result = {
                'conditions': {
                    'categories': categories_data
                },
                'pageData': {
                    'counts': total_count,
                    'pageSize': page_size,
                    'pages': total_pages,
                    'page': page,
                    'items': items
                }
            }

            return JsonResponse({
                'msg': '获取成功',
                'result': result
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'msg': '无效的请求数据格式',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'msg': f'搜索商品失败: {str(e)}',
                'result': None
            })

    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def cancel_order(request, id):
    if request.method == 'PUT':
        try:
            # 获取订单信息
            order = Order.objects.get(id=id)
            
            # 验证订单状态是否可以取消（只有待付款状态可以取消）
            if order.status != 'Processing':
                return JsonResponse({
                    'msg': '只有待付款的订单可以取消',
                    'result': None
                })
            
            # 获取取消原因
            data = json.loads(request.body)
            cancel_reason = data.get('cancelReason', '')
            
            # 恢复商品库存
            order_details = OrderDetail.objects.filter(order=order)
            for detail in order_details:
                product = detail.product
                product.stock += detail.quantity
                product.save()
            
            # 更新订单状态为已取消
            order.status = 'Closed'
            order.close_time = timezone.now()
            order.save()
            
            # 构建返回数据
            result = {
                'id': str(order.id),
                'createTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'payType': 1 if order.payment_method == '在线支付' else 2,
                'orderState': 'Closed',  # 已关闭
                'payLatestTime': '',
                'postFee': str(order.shipping_fee),
                'payMoney': str(order.total_amount),
                'payChannel': 1,
                'totalMoney': str(order.total_price),
                'totalNum': str(sum(detail.quantity for detail in order_details)),
                'deliveryTimeType': 1,
                'receiverContact': order.consignee_name,
                'receiverMobile': order.consignee_tel,
                'receiverAddress': order.consignee_addr,
                'payTime': '',
                'consignTime': '',
                'endTime': '',
                'closeTime': order.close_time.strftime('%Y-%m-%d %H:%M:%S'),
                'skus': [{
                    'id': str(detail.id),
                    'spuId': str(detail.product.id),
                    'name': detail.product.name,
                    'quantity': str(detail.quantity),
                    'image': detail.product.image.url if detail.product.image else '',
                    'curPrice': float(detail.price_at_time_of_purchase),
                    'totalMoney': float(detail.quantity * detail.price_at_time_of_purchase),
                    'realPay': float(detail.quantity * detail.price_at_time_of_purchase),
                    'properties': [{
                        'propertyMainName': '规格',
                        'propertyValueName': f'{detail.quantity}件'
                    }]
                } for detail in order_details]
            }
            
            return JsonResponse({
                'msg': '订单取消成功',
                'result': result
            })
            
        except Order.DoesNotExist:
            return JsonResponse({
                'msg': '订单不存在',
                'result': None
            })
        except json.JSONDecodeError:
            return JsonResponse({
                'msg': '无效的请求数据',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'msg': f'取消订单失败: {str(e)}',
                'result': None
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def receipt_order(request, id):
    if request.method == 'PUT':
        try:
            # 获取订单信息
            order = Order.objects.get(id=id)
            
            # 验证订单状态是否为待收货
            if order.status != 'Shipped':
                return JsonResponse({
                    'message': '订单状态不正确，无法确认收货',
                    'result': None
                })
            
            # 更新订单状态为待评价
            order.status = 'Pending_Review'
            order.end_time = timezone.now()
            order.save()
            
            # 构建返回数据
            order_details = OrderDetail.objects.filter(order=order)
            result = {
                'id': str(order.id),
                'createTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'payType': 1 if order.payment_method == '在线支付' else 2,
                'orderState': 'Delivered',  # 已送达状态
                'payLatestTime': '',
                'postFee': str(order.shipping_fee),
                'payMoney': str(order.total_amount),
                'payChannel': 1,  # 1支付宝、2微信
                'totalMoney': str(order.total_price),
                'totalNum': str(sum(detail.quantity for detail in order_details)),
                'deliveryTimeType': 1,  # 1为不限，2为工作日，3为双休或假日
                'receiverContact': order.consignee_name,
                'receiverMobile': order.consignee_tel,
                'receiverAddress': order.consignee_addr,
                'payTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'consignTime': order.consign_time.strftime('%Y-%m-%d %H:%M:%S') if order.consign_time else '',
                'endTime': order.end_time.strftime('%Y-%m-%d %H:%M:%S'),
                'closeTime': '',
                'skus': [{
                    'id': str(detail.id),
                    'spuId': str(detail.product.id),
                    'name': detail.product.name,
                    'quantity': str(detail.quantity),
                    'image': detail.product.image.url if detail.product.image else '',
                    'curPrice': float(detail.price_at_time_of_purchase),
                    'totalMoney': float(detail.quantity * detail.price_at_time_of_purchase),
                    'realPay': float(detail.quantity * detail.price_at_time_of_purchase),
                    'properties': [{
                        'propertyMainName': '规格',
                        'propertyValueName': f'{detail.quantity}件'
                    }]
                } for detail in order_details]
            }
            
            return JsonResponse({
                'message': '确认收货成功',
                'result': result
            })
            
        except Order.DoesNotExist:
            return JsonResponse({
                'msg': '订单不存在',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'确认收货失败: {str(e)}',
                'result': None
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def get_goods_relevant(request):
    if request.method == 'GET':
        try:
            # 获取请求参数
            product_id = request.GET.get('id')  # 商品ID（可选）
            limit = int(request.GET.get('limit', 4))  # 数量限制，默认4个
            
            # 限制返回数量不超过16
            limit = min(limit, 16)
            
            if product_id:
                # 相关商品推荐：根据当前商品的分类推荐同类商品
                current_product = Product.objects.get(id=product_id)
                products = Product.objects.filter(
                    category=current_product.category
                ).exclude(id=product_id)[:limit]
            else:
                # 猜你喜欢：随机推荐商品
                products = Product.objects.all().order_by('?')[:limit]
            
            # 构建返回数据
            result = [{
                'id': str(product.id),
                'picture': product.image.url if product.image else '',
                'name': product.name,
                'price': float(product.price),
                'desc': product.description[:10],  # 取描述的前10个字符作为简短描述
                'discount': round(random.uniform(0.1, 0.99), 2)  # 随机生成折扣信息
            } for product in products]
            
            return JsonResponse({
                'msg': '获取推荐商品成功',
                'result': result
            })
            
        except Product.DoesNotExist:
            return JsonResponse({
                'msg': '商品不存在',
                'result': []
            })
        except ValueError:
            return JsonResponse({
                'msg': '参数格式错误',
                'result': []
            })
        except Exception as e:
            return JsonResponse({
                'msg': f'获取推荐商品失败: {str(e)}',
                'result': []
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': []
    })

@csrf_exempt
def get_order_preview_now(request):
    if request.method == 'GET':
        try:
            # 获取请求参数
            sku_id = request.GET.get('skuId')
            count = int(request.GET.get('count', 1))
            address_id = request.GET.get('addressId')
            
            # 验证必要参数
            if not all([sku_id, count, address_id]):
                return JsonResponse({
                    'message': '缺少必要参数',
                    'result': None
                })
            
            # 获取商品信息
            try:
                product = Product.objects.get(id=sku_id)
            except Product.DoesNotExist:
                return JsonResponse({
                    'message': '商品不存在',
                    'result': None
                })
            
            # 检查库存
            if product.stock < count:
                return JsonResponse({
                    'message': '商品库存不足',
                    'result': None
                })
            
            # 获取用户地址列表
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'message': '用户未登录',
                    'result': None
                })
            
            try:
                user = User.objects.get(id=user_id)
                addresses = Address.objects.filter(user=user)
                selected_address = Address.objects.get(id=address_id, user=user)
            except (User.DoesNotExist, Address.DoesNotExist):
                return JsonResponse({
                    'message': '用户或地址信息不存在',
                    'result': None
                })
            
            # 构建地址列表
            address_list = [{
                'id': str(addr.id),
                'provinceCode': addr.province_code,
                'cityCode': addr.city_code,
                'countyCode': addr.county_code,
                'address': addr.detail,
                'isDefault': 0 if addr.is_default else 1,
                'selected': addr.id == selected_address.id
            } for addr in addresses]
            
            # 计算商品金额
            total_price = product.price * count
            post_fee = Decimal('10.00')  # 设置固定运费
            
            # 构建商品信息
            goods = [{
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'count': count,
                'skuId': str(product.id),
                'attrsText': '',
                'price': float(product.price),
                'payPrice': float(product.price),
                'totalPrice': float(total_price),
                'totalPayPrice': float(total_price)
            }]
            
            # 构建返回数据
            result = {
                'userAddresses': address_list,
                'goods': goods,
                'summary': {
                    'goodsCount': count,
                    'totalPrice': float(total_price),
                    'totalPayPrice': float(total_price),
                    'postFee': float(post_fee),
                    'discountPrice': 0
                }
            }
            
            return JsonResponse({
                'message': '获取成功',
                'result': result
            })
            
        except Exception as e:
            return JsonResponse({
                'message': f'获取订单预览失败: {str(e)}',
                'result': None
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def get_order_logistics(request, id):
    if request.method == 'GET':
        try:
            # 获取订单信息
            order = Order.objects.get(id=id)
            order_details = OrderDetail.objects.filter(order=order)
            
            # 获取第一个商品的信息作为展示
            first_product = order_details.first()
            if not first_product:
                return JsonResponse({
                    'message': '订单商品信息不存在',
                    'result': None
                })
            
            # 模拟物流信息（实际项目中应该对接物流公司的API）
            logistics_list = [
                {
                    'id': '1',
                    'text': '已签收,感谢使用顺丰快递',
                    'time': (timezone.now()).strftime('%Y-%m-%d %H:%M:%S')
                },
                {
                    'id': '2',
                    'text': '【北京市】快件已到达北京海淀区分部',
                    'time': (timezone.now() - timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S')
                },
                {
                    'id': '3',
                    'text': '【上海市】快件已从上海分拨中心发出',
                    'time': (timezone.now() - timedelta(days=2)).strftime('%Y-%m-%d %H:%M:%S')
                },
                {
                    'id': '4',
                    'text': '【上海市】快件已到达上海分拨中心',
                    'time': (timezone.now() - timedelta(days=2, hours=6)).strftime('%Y-%m-%d %H:%M:%S')
                },
                {
                    'id': '5',
                    'text': '【广州市】快件已从广州仓库发出',
                    'time': (timezone.now() - timedelta(days=3)).strftime('%Y-%m-%d %H:%M:%S')
                }
            ]
            
            # 构建返回数据
            result = {
                'picture': first_product.product.image.url if first_product.product.image else '',
                'count': first_product.quantity,
                'company': {
                    'name': '顺丰快递',
                    'number': f'SF{random.randint(100000000, 999999999)}',
                    'tel': '95338'
                },
                'list': logistics_list
            }
            
            return JsonResponse({
                'message': '获取物流信息成功',
                'result': result
            })
            
        except Order.DoesNotExist:
            return JsonResponse({
                'msg': '订单不存在',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'获取物流信息失败: {str(e)}',
                'result': None
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def repurchase_order(request, id):
    if request.method == 'GET':
        try:
            # 获取原订单信息
            order = Order.objects.get(id=id)
            order_details = OrderDetail.objects.filter(order=order)
            
            # 获取用户地址列表
            user_addresses = Address.objects.filter(user=order.user)
            addresses_list = [{
                'id': str(addr.id),
                'provinceCode': addr.province_code,
                'cityCode': addr.city_code,
                'countyCode': addr.county_code,
                'address': addr.detail,
                'isDefault': 0 if addr.is_default else 1
            } for addr in user_addresses]
            
            # 构建商品列表
            goods = []
            total_price = Decimal('0.00')
            total_pay_price = Decimal('0.00')
            goods_count = 0
            
            for detail in order_details:
                # 检查商品是否还存在且有库存
                try:
                    product = Product.objects.get(id=detail.product.id)
                    if product.stock > 0 and product.status == 'published':
                        item_total = detail.quantity * product.price
                        goods.append({
                            'id': str(product.id),
                            'name': product.name,
                            'picture': f'/{product.image.name}' if product.image else None,
                            'count': detail.quantity,
                            'skuId': str(product.id),
                            'attrsText': '',
                            'price': float(product.price),
                            'payPrice': float(product.price),
                            'totalPrice': float(item_total),
                            'totalPayPrice': float(item_total)
                        })
                        total_price += item_total
                        total_pay_price += item_total
                        goods_count += detail.quantity
                except Product.DoesNotExist:
                    continue
            
            # 计算运费（示例：固定运费10元）
            post_fee = Decimal('10.00')
            
            # 构建返回数据
            result = {
                'userAddresses': addresses_list,
                'goods': goods,
                'summary': {
                    'goodsCount': goods_count,
                    'totalPrice': float(total_price),
                    'totalPayPrice': float(total_pay_price),
                    'postFee': float(post_fee),
                    'discountPrice': 0
                }
            }
            
            return JsonResponse({
                'message': '获取成功',
                'result': result
            })
            
        except Order.DoesNotExist:
            return JsonResponse({
                'msg': '订单不存在',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'获取订单信息失败: {str(e)}',
                'result': None
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def get_order_detail(request, order_id):
    if request.method == 'GET':
        try:
            # 获取订单信息
            order = Order.objects.get(id=order_id)
            print("获取到的订单信息：", order)
            
            # 获取订单详情
            order_details = OrderDetail.objects.filter(order=order)
            print("获取到的订单详情：", order_details)
            skus = []
            total_num = 0
            for detail in order_details:
                # 计算商品属性
                properties = [
                    {
                        'propertyMainName': '规格',
                        'propertyValueName': f'{detail.quantity}件'
                    }
                ]
                
                skus.append({
                    'id': str(detail.id),
                    'spuId': str(detail.product.id),
                    'name': detail.product.name,
                    'quantity': str(detail.quantity),
                    'image': detail.product.image.url if detail.product.image else '',
                    'curPrice': float(detail.price_at_time_of_purchase),
                    'totalMoney': float(detail.quantity * detail.price_at_time_of_purchase),
                    'realPay': float(detail.quantity * detail.price_at_time_of_purchase),
                    'properties': properties
                })
                total_num += detail.quantity

            # 计算订单状态
            order_state_map = {
                'Processing': 'Processing',  # 待付款
                'Paid': 'Paid',  # 已付款
                'Confirmed': 'Confirmed',  # 已确认
                'Shipped': 'Shipped',  # 已发货
                'In_Transit': 'In_Transit',  # 运输中
                'Delivered': 'Delivered',  # 已送达
                'Completed': 'Completed',  # 已完成
                'Return': 'Return',  # 退货/退款中
                'Closed': 'Closed'  # 已关闭
            }
            order_state = order_state_map.get(order.status, 1)
            
            # 计算支付倒计时（假设订单有效期为24小时）
            if order.created_at:
                order_deadline = order.created_at + timezone.timedelta(hours=24)
                now = timezone.now()
                if now > order_deadline:
                    countdown = -1
                    pay_latest_time = 0
                else:
                    countdown = int((order_deadline - now).total_seconds())
                    pay_latest_time = countdown
            else:
                countdown = -1
                pay_latest_time = 0

            # 构建订单数据
            order_data = {
                'message': '获取订单详情成功',
                'result': {
                    'id': str(order.id),
                    'createTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S') if order.created_at else '',
                    'payType': 1 if order.payment_method == '在线支付' else 2,  # 1为在线支付，2为货到付款
                    'orderState': order_state,
                    'payLatestTime': pay_latest_time,
                    'countdown': countdown,
                    'postFee': str(order.shipping_fee),
                    'payMoney': str(order.total_amount),
                    'payChannel': 1,  # 1支付宝、2微信
                    'totalMoney': str(order.total_price),
                    'totalNum': str(total_num),
                    'deliveryTimeType': 1,  # 1为不限，2为工作日，3为双休或假日
                    'receiverContact': order.consignee_name,
                    'receiverMobile': order.consignee_tel,
                    'receiverAddress': order.consignee_addr,
                    'payTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S') if order.status != 'Pending' else '',
                    'consignTime': '',  # 发货时间，需要添加相应字段
                    'arrivalEstimatedTime': (timezone.now() + timezone.timedelta(days=3)).strftime('%Y-%m-%d') if order.status == 'Shipped' else '',
                    'endTime': '',  # 交易完成时间，需要添加相应字段
                    'closeTime': '',  # 交易关闭时间，需要添加相应字段
                    'evaluationTime': '',  # 评价时间，需要添加相应字段
                    'skus': skus
                }
            }

            return JsonResponse(order_data)
            
        except Order.DoesNotExist:
            return JsonResponse({
                'msg': '订单不存在',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'获取订单详情失败: {str(e)}',
                'result': None
            })
    
    elif request.method == 'POST':
        try:
            # 获取订单信息
            order = Order.objects.get(id=order_id)
            
            # 获取新的状态
            data = json.loads(request.body)
            print("获取到的订单信息：", order)
            print("获取到的新状态：", data)
            new_status = data.get('orderState')
            print("获取到的新状态11：", new_status)
            
            # 验证状态值是否合法
            valid_statuses = [
                'Processing', 'Paid', 'Confirmed', 'Shipped',
                'In_Transit', 'Delivered', 'Completed', 'Return', 'Closed'
            ]
            
            if not new_status or new_status not in valid_statuses:
                return JsonResponse({
                    'message': '无效的订单状态',
                    'result': None
                })
            
            # 更新订单状态
            order.status = new_status
            
            # 根据状态更新相关时间字段
            now = timezone.now()
            if new_status == 'Shipped':
                order.consign_time = now
            elif new_status == 'Completed':
                order.end_time = now
            elif new_status == 'Closed':
                order.close_time = now
            
            order.save()
            
            # 返回更新后的订单信息
            return JsonResponse({
                'message': '订单状态更新成功',
                'code': 200,
                'result': {
                    'id': str(order.id),
                    'status': new_status,
                    'updateTime': now.strftime('%Y-%m-%d %H:%M:%S')
                }
            })
            
        except Order.DoesNotExist:
            return JsonResponse({
                'message': '订单不存在',
                'result': None
            })
        except json.JSONDecodeError:
            return JsonResponse({
                'message': '无效的请求数据',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'更新订单状态失败: {str(e)}',
                'result': None
            })
            
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def update_cart_selected(request):
    if request.method == 'PUT':
        try:
            # 解析请求数据
            data = json.loads(request.body)
            user_id = data.get('user_id')
            selected = data.get('selected')
            ids = data.get('ids', [])

            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空'
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 根据是否提供ids参数来决定是全选/取消全选还是选择特定商品
            if not ids:
                # 全选/取消全选
                CartItem.objects.filter(user=user).update(selected=selected)
            else:
                # 更新指定商品的选中状态
                CartItem.objects.filter(user=user, product_id__in=ids).update(selected=selected)

            return JsonResponse({
                'code': 200,
                'message': '更新成功'
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据格式'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def update_cart_item(request, id):
    if request.method == 'PUT':
        try:
            # 解析请求数据
            data = json.loads(request.body)
            user_id = data.get('user_id')
            count = data.get('count')
            selected = data.get('selected')

            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空'
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 获取购物车项
            try:
                cart_item = CartItem.objects.get(user=user, product_id=id)
            except CartItem.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '购物车商品不存在'
                })

            # 更新购物车项
            if count is not None:
                cart_item.count = count
            if selected is not None:
                cart_item.selected = selected
            cart_item.save()

            # 构建返回数据
            product = cart_item.product
            result = {
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'count': cart_item.count,
                'skuId': str(product.id),
                'attrsText': '',
                'selected': cart_item.selected,
                'nowPrice': float(product.price),
                'stock': product.stock,
                'isCollect': False,
                'discount': 1,
                'isEffective': True if product.stock > 0 and product.status == 'published' else False
            }

            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'result': result
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据格式'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def cart_operations(request):
    if request.method == 'GET':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': []
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': []
                })

            # 获取用户的购物车商品列表
            cart_items = CartItem.objects.filter(user=user).select_related('product')
            
            # 构建返回数据
            result = [{
                'id': str(item.product.id),
                'name': item.product.name,
                'picture': item.product.image.name if item.product.image else None,
                'price': float(item.product.price),
                'count': item.count,
                'skuId': str(item.product.id),  # 使用商品ID作为skuId
                'attrsText': '',  # 商品属性文本，暂时为空
                'selected': item.selected,
                'nowPrice': float(item.product.price),  # 当前价格与原价相同
                'stock': item.product.stock,
                'isCollect': False,  # 收藏状态，默认为False
                'discount': 1,  # 折扣信息，默认为1（无折扣）
                'isEffective': True if item.product.stock > 0 and item.product.status == 'published' else False
            } for item in cart_items]

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': result
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取购物车列表失败: {str(e)}',
                'result': []
            })

    elif request.method == 'POST':
        try:
            data = json.loads(request.body)
            user_id = request.headers.get('x-user-id')
            sku_id = data.get('skuId')
            count = data.get('count')
            selected = data.get('selected', True)
            attrs_text = data.get('attrsText', '')

            # 验证必要参数
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空'
                })
            if not sku_id:
                return JsonResponse({
                    'code': 400,
                    'message': '商品ID不能为空'
                })
            if not count:
                return JsonResponse({
                    'code': 400,
                    'message': '商品数量不能为空'
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 获取商品信息
            try:
                product = Product.objects.get(id=sku_id)
            except Product.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '商品不存在'
                })

            # 验证库存
            if product.stock < count:
                return JsonResponse({
                    'code': 400,
                    'message': '库存不足'
                })

            # 获取或创建购物车项
            cart_item, created = CartItem.objects.get_or_create(
                user=user,
                product=product,
                defaults={
                    'count': count,
                    'selected': selected
                }
            )

            # 如果购物车项已存在，更新数量
            if not created:
                cart_item.count = count
                cart_item.selected = selected
                cart_item.save()

            # 构建响应数据
            response_data = {
                'id': str(product.id),
                'skuId': str(product.id),
                'name': product.name,
                'attrsText': attrs_text,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'nowPrice': float(product.price),
                'selected': cart_item.selected,
                'stock': product.stock,
                'count': cart_item.count,
                'discount': 1,
                'isCollect': False,
                'isEffective': True if product.stock > 0 and product.status == 'published' else False
            }

            return JsonResponse({
                'code': 200,
                'message': '添加成功',
                'result': response_data
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'服务器错误: {str(e)}'
            })
    
    elif request.method == 'DELETE':
        try:
            data = json.loads(request.body)
            user_id = request.headers.get('x-user-id')
            ids = data.get('ids', [])
            clear_all = data.get('clearAll', False)
            clear_invalid = data.get('clearInvalid', False)

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 获取用户的购物车项
            cart_items = CartItem.objects.filter(user=user)

            # 清空购物车
            if clear_all:
                cart_items.delete()
                return JsonResponse({
                    'code': 200,
                    'message': '购物车已清空'
                })

            # 清空无效商品
            if clear_invalid:
                invalid_items = cart_items.filter(product__stock=0)
                invalid_items.delete()
                return JsonResponse({
                    'code': 200,
                    'message': '无效商品已清空'
                })

            # 删除指定商品
            if ids:
                cart_items.filter(product_id__in=ids).delete()
                return JsonResponse({
                    'code': 200,
                    'message': '删除成功'
                })

            return JsonResponse({
                'code': 200,
                'message': '操作成功'
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'服务器错误: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def get_cart_multi(request):
    if request.method == 'GET':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': {'valids': [], 'invalids': []}
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': {'valids': [], 'invalids': []}
                })

            # 获取用户的购物车商品列表
            cart_items = CartItem.objects.filter(user=user).select_related('product')
            
            # 分离有效和无效商品
            valids = []
            invalids = []
            
            for item in cart_items:
                product_data = {
                    'id': str(item.product.id),
                    'name': item.product.name,
                    'picture': item.product.image.name if item.product.image else None,
                    'price': float(item.product.price),
                    'count': item.count,
                    'skuId': str(item.product.id),
                    'attrsText': '',  # 商品属性文本
                    'selected': item.selected,
                    'nowPrice': float(item.product.price),
                    'stock': item.product.stock,
                    'isCollect': False,
                    'discount': 1
                }
                
                # 如果商品有效（有库存且已发布），添加到有效商品列表
                if item.product.stock > 0 and item.product.status == 'published':
                    # 添加规格信息
                    product_data['specs'] = [
                        {
                            'name': '规格',
                            'valueName': '默认',
                            'selected': True
                        }
                    ]
                    valids.append(product_data)
                else:
                    invalids.append(product_data)

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': {
                    'valids': valids,
                    'invalids': invalids
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取购物车列表失败: {str(e)}',
                'result': {'valids': [], 'invalids': []}
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许',
        'result': {'valids': [], 'invalids': []}
    })

@csrf_exempt
def get_cart_count(request):
    if request.method == 'GET':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': {'count': 0}
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': {'count': 0}
                })

            # 获取用户购物车中的商品总数量
            total_count = CartItem.objects.filter(user=user).aggregate(total=Sum('count'))['total'] or 0

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': {'count': total_count}
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取购物车数量失败: {str(e)}',
                'result': {'count': 0}
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许',
        'result': {'count': 0}
    })

@csrf_exempt
def delete_address(request, id):
    if request.method == 'DELETE':
        try:
            # 验证用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空'
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 获取并删除地址
            try:
                address = Address.objects.get(id=id, user=user)
                address.delete()
                return JsonResponse({
                    'code': 200,
                    'message': '删除成功'
                })
            except Address.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '地址不存在'
                })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'删除失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def get_user_orders(request):
    if request.method == 'GET':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': None
                })

            # 获取分页参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('pageSize', 10))
            order_state = request.GET.get('orderState', '0')

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': None
                })

            # 获取用户订单
            orders = Order.objects.filter(user=user)

            # 根据订单状态过滤
            if order_state != '0':
                orders = orders.filter(status=order_state)

            # 计算分页
            total_count = orders.count()
            total_pages = (total_count + page_size - 1) // page_size
            start = (page - 1) * page_size
            end = start + page_size
            paginated_orders = orders[start:end]

            # 构建返回数据
            items = []
            for order in paginated_orders:
                order_details = OrderDetail.objects.filter(order=order)
                skus = []
                for detail in order_details:
                    skus.append({
                        'id': str(detail.product.id),
                        'spuId': str(detail.product.id),
                        'name': detail.product.name,
                        'quantity': detail.quantity,
                        'image': f'/{detail.product.image.name}' if detail.product.image else None,
                        'realPay': float(detail.price_at_time_of_purchase * detail.quantity),
                        'properties': [{
                            'propertyMainName': '规格',
                            'propertyValueName': '默认',
                            'attrsText': '规格:默认'
                        }]
                    })

                # 计算倒计时（示例逻辑，实际应根据业务需求调整）
                countdown = -1
                if order.status == 'Processing':  # 待付款
                    countdown = 1800  # 30分钟倒计时

                items.append({
                    'id': str(order.id),
                    'createTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'payType': 1 if order.payment_method == 'online' else 2,
                    'orderState': order.status,
                    'payLatestTime': (order.created_at + timedelta(minutes=30)).strftime('%Y-%m-%d %H:%M:%S'),
                    'countdown': countdown,
                    'postFee': float(order.shipping_fee),
                    'payMoney': float(order.total_amount),
                    'totalMoney': float(order.total_amount + order.shipping_fee),
                    'totalNum': str(order_details.aggregate(total=Sum('quantity'))['total'] or 0),
                    'skus': skus
                })

            return JsonResponse({
                'message': '获取成功',
                'result': {
                    'counts': total_count,
                    'pageSize': str(page_size),
                    'pages': str(total_pages),
                    'page': str(page),
                    'items': items
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取订单列表失败: {str(e)}',
                'result': None
            })

    elif request.method == 'POST':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': None
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': None
                })

            # 解析请求数据
            data = json.loads(request.body)
            print("data:的数据111", data)
            address_id = data.get('addressId')
            goods = data.get('goods', [])
            delivery = data.get('delivery', 0)  # 配送方式
            payment_type = data.get('payType', 1)  # 支付方式

            # 验证必要字段
            if not address_id or not goods:
                return JsonResponse({
                    'code': 400,
                    'message': '缺少必要参数',
                    'result': None
                })

            # 获取收货地址
            try:
                address = Address.objects.get(id=address_id, user=user)
            except Address.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '收货地址不存在',
                    'result': None
                })

            # 创建订单
            total_price = data.get('totalPrice', 0)
            order = Order.objects.create(
                user=user,
                status='Processing',  # 待付款状态
                payment_method='online' if payment_type == 1 else 'offline',
                shipping_fee=0.00,  # 运费
                total_amount=0.00,  # 初始化总金额
                total_price=total_price,  # 设置订单总价
                consignee_addr=f'{address.province_code} {address.city_code} {address.county_code} {address.detail}',
                consignee_name=address.receiver,
                consignee_tel=address.phone
            )

            # 处理订单商品
            total_amount = 0
            for item in goods:
                try:
                    product = Product.objects.get(id=item['id'])
                    quantity = item['count']

                    # 检查库存
                    if product.stock < quantity:
                        order.delete()
                        return JsonResponse({
                            'code': 400,
                            'message': f'商品 {product.name} 库存不足',
                            'result': None
                        })

                    # 创建订单详情
                    OrderDetail.objects.create(
                        order=order,
                        product=product,
                        quantity=quantity,
                        price_at_time_of_purchase=product.price
                    )

                    # 更新总金额
                    total_amount += product.price * quantity

                    # 更新库存
                    product.stock -= quantity
                    product.save()

                except Product.DoesNotExist:
                    order.delete()
                    return JsonResponse({
                        'code': 404,
                        'message': f'商品不存在',
                        'result': None
                    })

            # 更新订单总金额
            order.total_amount = total_amount
            order.save()

            # 清空已购买的购物车商品
            CartItem.objects.filter(user=user, product_id__in=[item['id'] for item in goods]).delete()

            return JsonResponse({
                'code': 200,
                'message': '订单创建成功',
                'result': {
                    'orderId': str(order.id)
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据格式',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'创建订单失败: {str(e)}',
                'result': None
            })

    elif request.method == 'DELETE':
        try:
            # 获取请求数据
            data = json.loads(request.body)
            order_ids = data.get('ids', [])

            if not order_ids:
                return JsonResponse({
                    'message': '请选择要删除的订单',
                    'result': None
                })

            # 获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'message': '用户未登录',
                    'result': None
                })

            # 获取用户的订单
            user_orders = Order.objects.filter(
                id__in=order_ids,
                user_id=user_id,
                status__in=['Completed', 'Cancelled']
            )

            # 检查是否所有订单都存在且状态正确
            if len(user_orders) != len(order_ids):
                return JsonResponse({
                    'message': '部分订单不存在或状态不允许删除',
                    'result': None
                })

            # 删除订单及关联的订单详情
            for order in user_orders:
                OrderDetail.objects.filter(order=order).delete()
                order.delete()

            return JsonResponse({
                'message': '订单删除成功',
                'result': None
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'msg': '无效的请求数据',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'删除订单失败: {str(e)}',
                'result': None
            })

    return JsonResponse({
        'code': 405,
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def get_address_list(request):
    if request.method == 'GET':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': None
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': None
                })

            # 获取用户地址列表
            addresses = user.addresses.all()
            address_list = [{
                'id': str(address.id),
                'receiver': address.receiver,
                'provinceCode': address.province_code,
                'cityCode': address.city_code,
                'countyCode': address.county_code,
                'address': address.detail,
                'isDefault': 0 if address.is_default else 1,
                'contact': address.phone,
                'postalCode': address.postal_code,
                'addressTags': address.tags,
                'fullLocation': f'{address.province_code} {address.city_code} {address.county_code}'
            } for address in addresses]

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': address_list
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取地址列表失败: {str(e)}',
                'result': None
            })

    return JsonResponse({
        'code': 405,
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def consignment_order(request, id):
    if request.method == 'GET':
        try:
            # 获取订单信息
            order = Order.objects.get(id=id)
            
            # 验证订单状态
            if order.status != 'Processing':
                return JsonResponse({
                    'message': '订单状态不正确，无法发货',
                    'result': None
                })
            
            # 更新订单状态为已发货
            order.status = 'Shipped'
            order.consign_time = timezone.now()
            order.save()
            
            # 构建返回数据
            result = {
                'id': str(order.id),
                'createTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'payType': 1 if order.payment_method == '在线支付' else 2,
                'orderState': 3,  # 3表示待收货状态
                'payLatestTime': 0,
                'postFee': str(order.shipping_fee),
                'payMoney': str(order.total_amount),
                'payChannel': 1,  # 1支付宝、2微信
                'totalMoney': str(order.total_price),
                'totalNum': OrderDetail.objects.filter(order=order).aggregate(total=Sum('quantity'))['total'] or 0,
                'deliveryTimeType': 1,  # 1为不限，2为工作日，3为双休或假日
                'receiverContact': order.consignee_name,
                'receiverMobile': order.consignee_tel,
                'receiverAddress': order.consignee_addr,
                'payTime': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'consignTime': order.consign_time.strftime('%Y-%m-%d %H:%M:%S'),
                'arrivalEstimatedTime': (timezone.now() + timedelta(days=3)).strftime('%Y-%m-%d'),
                'endTime': '',
                'closeTime': '',
                'evaluationTime': ''
            }
            
            return JsonResponse({
                'message': '发货成功',
                'result': result
            })
            
        except Order.DoesNotExist:
            return JsonResponse({
                'msg': '订单不存在',
                'result': None
            })
        except Exception as e:
            return JsonResponse({
                'message': f'发货失败: {str(e)}',
                'result': None
            })
    
    return JsonResponse({
        'msg': '方法不允许',
        'result': None
    })

@csrf_exempt
def get_order_preview(request):
    if request.method == 'GET':
        try:
            # 从请求头获取用户ID
            user_id = request.headers.get('x-user-id')
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '用户ID不能为空',
                    'result': None
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在',
                    'result': None
                })

            # 获取用户地址列表
            addresses = user.addresses.all()
            address_list = [{
                'id': str(address.id),
                'provinceCode': address.province_code,
                'cityCode': address.city_code,
                'countyCode': address.county_code,
                'address': address.detail,
                'isDefault': 0 if address.is_default else 1,
                'receiver': address.receiver,
                'contact': address.phone,
                'fullLocation': f'{address.province_code} {address.city_code} {address.county_code}',
                'postalCode': address.postal_code
            } for address in addresses]

            # 获取购物车中选中的商品
            cart_items = CartItem.objects.filter(user=user, selected=True).select_related('product')
            goods_list = [{
                'id': str(item.product.id),
                'name': item.product.name,
                'picture': f'/{item.product.image.name}' if item.product.image else None,
                'count': item.count,
                'skuId': str(item.product.id),
                'attrsText': '',
                'price': float(item.product.price),
                'payPrice': float(item.product.price),
                'totalPrice': float(item.product.price * item.count),
                'totalPayPrice': float(item.product.price * item.count)
            } for item in cart_items]

            # 计算总价
            goods_count = len(goods_list)
            total_price = sum(item['totalPrice'] for item in goods_list)
            total_pay_price = total_price  # 假设没有折扣
            post_fee = 0.00  # 假设免邮费
            discount_price = 0.00  # 假设没有折扣

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': {
                    'userAddresses': address_list,
                    'goods': goods_list,
                    'summary': {
                        'goodsCount': goods_count,
                        'totalPrice': total_price,
                        'totalPayPrice': total_pay_price,
                        'postFee': post_fee,
                        'discountPrice': discount_price
                    }
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取订单预览失败: {str(e)}',
                'result': None
            })

    return JsonResponse({
        'code': 405,
        'msg': '方法不允许',
        'result': None
    })

from Manage_the_backend import settings
from .models import Product, User, Category, Order, OrderDetail, Role, Permission, CategoryHead, CategoryHeadChild
from rest_framework_simplejwt.tokens import RefreshToken
from django.shortcuts import get_object_or_404

@csrf_exempt
def get_category_products(request):
    if request.method == 'GET':
        try:
            # 获取分类ID
            category_id = request.GET.get('id')
            print(f"接收到的分类ID: {category_id}")
            if not category_id:
                return JsonResponse({
                    'code': 400,
                    'message': '分类ID不能为空'
                })

            # 检查分类是否存在
            try:
                category = Category.objects.get(id=category_id)
                print(f"找到分类: {category.name}")
            except Category.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': f'分类ID {category_id} 不存在'
                })
            except ValueError:
                return JsonResponse({
                    'code': 400,
                    'message': f'无效的分类ID格式: {category_id}'
                })

            # 获取该分类下的所有商品
            products = Product.objects.filter(category_id=category_id, status='published')
            print(f"查询到的商品数量: {products.count()}")
            
            # 如果没有找到商品，返回详细信息
            if not products.exists():
                return JsonResponse({
                    'code': 200,
                    'message': f'分类 {category.name} 下暂无已发布的商品',
                    'data': []
                })
            
            # 转换为列表格式
            result = [{
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'description': product.description,
                'stock': product.stock,
                'category': product.category.name,
                'created_at': product.created_at.strftime('%Y-%m-%d %H:%M:%S')
            } for product in products]
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': result
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取分类商品失败: {str(e)}'
            })
    
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def get_banner(request):
    if request.method == 'GET':
        try:
            # 获取广告区域展示位置参数，默认为1（首页）
            distribution_site = int(request.GET.get('distributionSite', 1))
            
            # 从Banner模型中获取对应位置的广告数据
            from .banner_models import Banner
            banners = Banner.objects.filter(distributionSite=distribution_site)[:5]
            
            # 构建返回数据
            result = [{
                'id': str(banner.id),
                'imgUrl': banner.imgUrl,
                'hrefUrl': banner.hrefUrl,
                'type': banner.type
            } for banner in banners]
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': result
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取广告数据失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

def merge_cart(request):
    if request.method == 'POST':
        try:
            # 获取请求数据
            data = json.loads(request.body)
            user_id = data.get('user_id')
            cart_items = data.get('cart_items', [])

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 处理每个购物车项
            for item in cart_items:
                product_id = item.get('product_id')
                count = item.get('count', 1)

                try:
                    product = Product.objects.get(id=product_id)
                    # 检查是否已存在相同商品的购物车项
                    cart_item, created = CartItem.objects.get_or_create(
                        user=user,
                        product=product,
                        defaults={'count': count}
                    )

                    if not created:
                        # 如果购物车项已存在，更新数量
                        cart_item.count += count
                        cart_item.save()

                except Product.DoesNotExist:
                    continue

            return JsonResponse({
                'code': 200,
                'message': '购物车合并成功'
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据格式'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'服务器错误: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def get_goods_detail(request):
    if request.method == 'GET':
        try:
            # 获取商品ID
            goods_id = request.GET.get('id')
            if not goods_id:
                return JsonResponse({
                    'code': 400,
                    'message': '商品ID不能为空'
                })

            # 获取商品详情
            try:
                product = Product.objects.get(id=goods_id)
            except Product.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '商品不存在'
                })

            # 构建商品详情数据
            image_url = f'/{product.image.name}' if product.image else None
            result = {
                'id': str(product.id),
                'name': product.name,
                'picture': image_url,  # 保留原有的picture字段
                'mainPictures': [image_url] if image_url else [],  # 添加mainPictures字段
                'price': float(product.price),
                'description': product.description,
                'stock': product.stock,
                'category': product.category.name,
                'status': product.status,
                'created_at': product.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': product.updated_at.strftime('%Y-%m-%d %H:%M:%S') if product.updated_at else None
            }

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': result
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取商品详情失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

def get_hot(request):
    if request.method == 'GET':
        try:
            # 获取指定的商品
            specific_products = ['人参', '薄荷','菊花', '灵芝']
            hot_products = Product.objects.filter(name__in=specific_products, status='published')
            
            # 转换为列表格式
            result = [{
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'description': product.description
            } for product in hot_products]
            
            return JsonResponse({
                'code': 200,
                'message': '获取热门推荐成功',
                'result': result
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取热门推荐失败: {str(e)}'
            })
            
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


def get_new(request):
    if request.method == 'GET':
        try:
            # 获取指定的商品
            specific_products = ['肉桂', '牵牛子','黄芪', '山茱萸']
            new_products = Product.objects.filter(name__in=specific_products, status='published')
            
            # 转换为列表格式
            result = [{
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'description': product.description
            } for product in new_products]
            
            return JsonResponse({
                'code': 200,
                'message': '获取新品推荐成功',
                'result': result
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取新品推荐失败: {str(e)}'
            })
            
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def get_home_goods(request):
    if request.method == 'GET':
        try:
            # 获取最新添加的商品（按创建时间倒序排序，限制8个）
            products = Product.objects.filter(status='published').order_by('-created_at')[:]
            
            # 转换为列表格式
            result = [{
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'description': product.description
            } for product in products]
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': result
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取首页商品数据失败: {str(e)}',
                'result': []
            })
    
    return JsonResponse({
        'code': 405,
        'message': '方法不允许',
        'result': []
    })

@csrf_exempt
def get_category_head(request):
    if request.method == 'GET':
        try:
            # 获取所有主分类（parent_category为空的分类）
            main_categories = Category.objects.filter(parent_category__isnull=True)
            
            result = []
            for category in main_categories:
                # 获取子分类及其商品
                children = []
                for sub_category in category.subcategories.all()[:10]:
                    # 获取该子分类下的商品
                    products = Product.objects.filter(category=sub_category, status='published')[:5]
                    goods = [{
                        'id': str(product.id),
                        'name': product.name,
                        'desc': product.description,
                        'price': str(product.price),
                        'picture': f'/{product.image.name}' if product.image else ''
                    } for product in products]
                    
                    children.append({
                        'id': str(sub_category.id),
                        'name': sub_category.name,
                        'picture': f'/{sub_category.image.name}' if hasattr(sub_category, 'image') and sub_category.image else '',
                        'goods': goods
                    })
                
                result.append({
                    'id': str(category.id),
                    'name': category.name,
                    'children': children
                })
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'result': result
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取分类数据失败: {str(e)}',
                'result': []
            })
    
    return JsonResponse({
        'code': 405,
        'message': '方法不允许',
        'result': []
    })

@csrf_exempt
def delete_category(request, id):
    if request.method == 'DELETE':
        try:
            # 获取要删除的分类对象
            category = Category.objects.get(id=id)
            # 删除分类
            category.delete()
            return JsonResponse({
                'code': 200,
                'message': '分类删除成功'
            })
        except Category.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '分类不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'分类删除失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def register(request):
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            email = request.POST.get('email')
            phone_number = request.POST.get('phone_number')
            # print(username, password, email, phone_number)
            # 验证用户名是否已存在
            if User.objects.filter(username=username).exists():
                return JsonResponse({
                    'code': 400,
                    'message': '用户名已存在'
                })

            # 创建新用户
            user = User.objects.create(
                username=username,
                password_hash=make_password(password),
                email=email,
                phone_number=phone_number
            )

            return JsonResponse({
                'code': 200,
                'message': '注册成功',
                'data': {
                    'user_id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phone_number': user.phone_number
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'注册失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def user_list(request):
    if request.method == 'GET':
        users = User.objects.all()
        users_list = list(users.values('id', 'username', 'email', 'phone_number', 'created_at','mg_state', 'role_name', 'role_description'))
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': users_list
        })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def login(request):
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            print("用户名",username, "密码",password)
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 400,
                    'message': '用户名不存在'
                })

            if check_password(password, user.password_hash):
                # 生成token
                refresh = RefreshToken.for_user(user)
                
                # 获取用户权限
                try:
                    role = Role.objects.get(name=user.role_description)
                    permissions = list(role.permissions.values_list('name', flat=True))
                    functions = role.functions.split(', ') if role.functions else []
                except Role.DoesNotExist:
                    permissions = []
                    functions = []
                # print("用户的权限为:", permissions)
                print("用户的功能为:", functions)
                return JsonResponse({
                    'code': 200,
                    'message': '登录成功',
                    'data': {
                        'token': str(refresh.access_token),
                        'user_id': user.id,
                        'username': user.username,
                        'email': user.email,
                        'phone_number': user.phone_number,
                        # 'permissions': permissions,
                        'functions': functions,  # 权限
                        'role': user.role_name
                    }
                })
            else:
                return JsonResponse({
                    'code': 400,
                    'message': '密码错误'
                })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'登录失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


def get_menu(request):
    # 获取用户列表数据
    users = User.objects.all()
    users_list = list(users.values('id', 'username', 'email', 'phone_number', 'created_at'))

    # 获取商品列表数据
    products = Product.objects.all()
    products_list = list(products.values())

    # 获取订单列表数据
    orders = Order.objects.all()
    orders_list = []
    for order in orders:
        order_details = OrderDetail.objects.filter(order=order)
        details = []
        for detail in order_details:
            details.append({
                'product_name': detail.product.name,
                'quantity': detail.quantity,
                'price': str(detail.price_at_time_of_purchase)
            })

        orders_list.append({
            'id': order.id,
            'user': order.user.username,
            'total_price': str(order.total_price),
            'status': order.status,
            'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'details': details
        })

    menu = [
        {
            'id': 1,
            'name': '用户管理',
            'children': [
                {'id': 101, 'name': '用户列表', 'url': '/user/list/', 'data': users_list},
            ]
        },
        {
            'id': 2,
            'name': '权限管理',
            'children': [
                {'id': 201, 'name': '角色列表', 'url': '/api/roles/', 'data': '角色列表'},
                {'id': 202, 'name': '权限列表', 'url': '/api/permissions/', 'data': '权限列表'},
            ]
        },
        {
            'id': 3,
            'name': '商品管理',
            'children': [
                {'id': 301, 'name': '商品列表', 'url': '/api/products/', 'data': products_list},
                # {'id': 302, 'name': '分类参数', 'url': '/api/category_params/', 'data': '分类参数'},
                {'id': 303, 'name': '商品分类', 'url': '/api/categories/', 'data': '商品分类'},
            ]
        },
        {
            'id': 4,
            'name': '订单管理',
            'children': [
                {'id': 401, 'name': '订单列表', 'url': '/api/orders/', 'data': orders_list},
            ]
        },
        {
            'id': 5,
            'name': '数据统计',
            'children': [
                {'id': 501, 'name': '数据报表', 'url': '/api/statistics/', 'data': '数据报表'},
            ]
        }
    ]
    return JsonResponse({
        'code': 200,
        'message': '获取成功',
        'data': menu
    })


# 商品管理接口
@csrf_exempt
def product_list_create(request):
    if request.method == 'GET':
        # 获取商品列表，支持分页和搜索
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        search = request.GET.get('search', '')
        category_id = request.GET.get('category_id')

        # 获取所有分类信息，并统计每个分类下的商品数量
        categories = Category.objects.all()
        categories_list = []
        for category in categories:
            # 获取该分类下的商品数量
            product_count = Product.objects.filter(category=category).count()
            
            # 获取该分类下的前5个商品作为预览
            preview_products = Product.objects.filter(category=category)[:5]
            preview_list = [{
                'id': product.id,
                'name': product.name,
                'price': str(product.price),
                'image': product.image.url if product.image else None,
            } for product in preview_products]

            categories_list.append({
                'id': category.id,
                'name': category.name,
                'parent_category': category.parent_category.name if category.parent_category else None,
                'description': category.description,
                'status': category.status,
                'created_at': category.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'updated_at': category.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
                'product_count': product_count,
                'preview_products': preview_list,
                'level': '一级'
            })

        # 获取分页的商品列表
        products = Product.objects.all()
        if search:
            products = products.filter(name__icontains=search)
        if category_id:
            products = products.filter(category_id=category_id)

        # 计算分页
        start = (page - 1) * page_size
        end = start + page_size
        paginated_products = products[start:end]

        # 构建商品列表数据
        products_list = [{
            'id': product.id,
            'name': product.name,
            'description': product.description,
            'price': str(product.price),
            'stock': product.stock,
            'category': product.category.name,
            'image': product.image.url if product.image else None,
            'status': product.status,
            'created_at': product.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'updated_at': product.updated_at.strftime('%Y-%m-%d %H:%M:%S'),
            'level': '二级'
        } for product in paginated_products]

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'categories': categories_list,
                'list': products_list,
                'total': products.count(),
                'page': page,
                'page_size': page_size
            }
        })

    elif request.method == 'POST':
        try:
            name = request.POST.get('name')
            description = request.POST.get('description')
            price = request.POST.get('price')
            stock = request.POST.get('stock')
            image = request.FILES.get('image')  # 获取上传的图片文件
            category_id = request.POST.get('category_id')

            # 检查商品名称是否已存在
            if Product.objects.filter(name=name).exists():
                return JsonResponse({
                    'code': 400,
                    'message': '商品名称已存在'
                })

            product = Product.objects.create(
                name=name,
                description=description,
                price=Decimal(price),
                stock=int(stock),
                image=image if image else None,  # 处理图片为空的情况
                category_id=category_id
            )

            return JsonResponse({
                'code': 200,
                'message': '创建成功',
                'data': {
                    'id': product.id,
                    'name': product.name,
                    'price': str(product.price),
                    'stock': product.stock
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'创建失败: {str(e)}'
            })

    elif request.method == 'PUT':
        print("put犯法")
        try:
            # 解析请求体中的 JSON 数据
            import json
            data = json.loads(request.body)
            print("传过来的数据",data)

            # 获取商品 ID
            product_id = data.get('id')
            if not product_id:
                return JsonResponse({
                    'code': 400,
                    'message': '商品 ID 不能为空'
                })

            # 获取商品对象
            try:
                product = Product.objects.get(id=product_id)
            except Product.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '商品不存在'
                })

            # 更新商品信息
            product.name = data.get('name', product.name)
            product.description = data.get('description', product.description)
            if 'price' in data:
                product.price = Decimal(data.get('price'))
            if 'stock' in data:
                product.stock = int(data.get('stock'))
            if 'category_id' in data:
                product.category_id = data.get('category_id')
            if 'image' in request.FILES:
                product.image = request.FILES.get('image')

            product.save()

            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'id': product.id,
                    'name': product.name,
                    'price': str(product.price),
                    'stock': product.stock
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })

@csrf_exempt
def delete_products(request, pk):
    if request.method == 'DELETE':
        try:
            product = Product.objects.get(pk=pk)
            product.delete()
            return JsonResponse({
                'code': 200,
                'message': '删除成功'
            })
        except Product.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '产品不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
               'message': f'删除失败: {str(e)}'
            })

@csrf_exempt
def product_detail(request, pk):
    try:
        product = Product.objects.get(pk=pk)
    except Product.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'message': '商品不存在'
        })

    if request.method == 'GET':
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': product.id,
                'name': product.name,
                'description': product.description,
                'price': str(product.price),
                'stock': product.stock,
                'image': product.image.url if product.image else None,
                'category_id': product.category_id
            }
        })

    elif request.method == 'PUT':
        try:
            product.name = request.POST.get('name', product.name)
            product.description = request.POST.get('description', product.description)
            if 'price' in request.POST:
                product.price = Decimal(request.POST.get('price'))
            if 'stock' in request.POST:
                product.stock = int(request.POST.get('stock'))
            if 'category_id' in request.POST:
                product.category_id = request.POST.get('category_id')

            product.save()

            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'id': product.id,
                    'name': product.name,
                    'price': str(product.price),
                    'stock': product.stock
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })

    elif request.method == 'DELETE':
        try:
            product.delete()
            return JsonResponse({
                'code': 200,
                'message': '删除成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'删除失败: {str(e)}'
            })


# 分类管理接口
@csrf_exempt
def category_list_create(request):
    if request.method == 'GET':
        try:
            # 获取请求参数
            page = int(request.GET.get('pagenum', 1))  # 当前页码，默认第一页
            page_size = int(request.GET.get('pagesize', 50))  # 每页显示条数，默认10条

            # 查询分类数据
            categories = Category.objects.all()

            # 分页处理
            start = (page - 1) * page_size
            end = start + page_size
            categories_list = list(categories[start:end].values('id', 'name'))
            total = categories.count()

            # 构建响应数据
            data = {
                'list': categories_list,
                'total': total,
                'page': page,
                'page_size': page_size
            }

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': data
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取失败: {str(e)}'
            })

    elif request.method == 'POST':
        try:
            name = request.POST.get('name')
            category = Category.objects.create(name=name)
            return JsonResponse({
                'code': 200,
                'message': '创建成功',
                'data': {
                    'id': category.id,
                    'name': category.name
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'创建失败: {str(e)}'
            })


@csrf_exempt
def category_detail(request, pk):
    try:
        category = Category.objects.get(pk=pk)
    except Category.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'message': '分类不存在'
        })

    if request.method == 'GET':
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': category.id,
                'name': category.name
            }
        })

    elif request.method == 'PUT':
        try:
            category.name = request.POST.get('name', category.name)
            category.save()
            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'id': category.id,
                    'name': category.name
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })

    elif request.method == 'DELETE':
        try:
            category.delete()
            return JsonResponse({
                'code': 200,
                'message': '删除成功'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'删除失败: {str(e)}'
            })


# 订单管理接口
@csrf_exempt
def order_list_create(request):
    if request.method == 'GET':
        # 获取订单列表，支持分页和搜索
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 10))
        status = request.GET.get('status')

        orders = Order.objects.all()
        if status:
            orders = orders.filter(status=status)

        start = (page - 1) * page_size
        end = start + page_size

        orders_list = []
        for order in orders[start:end]:
            order_details = OrderDetail.objects.filter(order=order)
            details = []
            for detail in order_details:
                details.append({
                    'product_name': detail.product.name,
                    'quantity': detail.quantity,
                    'price': str(detail.price_at_time_of_purchase)
                })

            orders_list.append({
                'id': order.id,
                'user': order.user.username,
                'total_price': str(order.total_price),
                'status': order.status,
                'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'details': details
            })

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'list': orders_list,
                'total': orders.count(),
                'page': page,
                'page_size': page_size
            }
        })
    
    elif request.method == 'POST':
        try:
            # 解析请求数据
            data = json.loads(request.body)
            user_id = data.get('user_id')
            products = data.get('products', [])
            shipping_fee = Decimal(str(data.get('shipping_fee', 0)))
            consignee_name = data.get('consignee_name')
            consignee_tel = data.get('consignee_tel')
            consignee_addr = data.get('consignee_addr')
            payment_method = data.get('payment_method')

            # 验证必要参数
            if not user_id or not products or not consignee_name or not consignee_tel or not consignee_addr:
                return JsonResponse({
                    'code': 400,
                    'message': '缺少必要参数'
                })

            # 验证用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 计算订单总价
            total_price = Decimal('0')
            order_details = []

            for product_data in products:
                product_id = product_data.get('skuId')  # 使用skuId作为product_id
                quantity = product_data.get('count', 1)  # 使用count作为数量

                try:
                    product = Product.objects.get(id=product_id)
                    if product.stock < quantity:
                        return JsonResponse({
                            'code': 400,
                            'message': f'商品 {product.name} 库存不足'
                        })

                    # 计算商品总价
                    item_total = product.price * Decimal(str(quantity))
                    total_price += item_total

                    # 准备订单详情数据
                    order_details.append({
                        'product': product,
                        'quantity': quantity,
                        'price_at_time_of_purchase': product.price
                    })

                except Product.DoesNotExist:
                    return JsonResponse({
                        'code': 404,
                        'message': f'商品ID {product_id} 不存在'
                    })

            # 创建订单
            order = Order.objects.create(
                user=user,
                total_price=total_price,
                shipping_fee=shipping_fee,
                total_amount=total_price + shipping_fee,
                consignee_name=consignee_name,
                consignee_tel=consignee_tel,
                consignee_addr=consignee_addr,
                payment_method=payment_method,
                status='pending',  # 设置初始状态为待付款
                fapiao_company='',  # 设置默认值
                fapiao_content='',  # 设置默认值
                fapiao_title=''  # 设置默认值
            )

            # 创建订单详情并更新库存
            for detail in order_details:
                OrderDetail.objects.create(
                    order=order,
                    product=detail['product'],
                    quantity=detail['quantity'],
                    price_at_time_of_purchase=detail['price_at_time_of_purchase']
                )
                # 更新库存
                product = detail['product']
                product.stock -= detail['quantity']
                product.save()

            return JsonResponse({
                'code': 200,
                'message': '订单创建成功',
                'data': {
                    'order_id': order.id,
                    'total_price': str(order.total_price),
                    'total_amount': str(order.total_amount),
                    'shipping_fee': str(order.shipping_fee)
                }
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据格式'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'创建订单失败: {str(e)}'
            })


@csrf_exempt
def order_detail(request, pk):
    try:
        order = Order.objects.get(pk=pk)
    except Order.DoesNotExist:
        return JsonResponse({
            'code': 404,
            'message': '订单不存在'
        })

    if request.method == 'GET':
        order_details = OrderDetail.objects.filter(order=order)
        details = []
        for detail in order_details:
            details.append({
                'product_name': detail.product.name,
                'quantity': detail.quantity,
                'price': str(detail.price_at_time_of_purchase)
            })

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'id': order.id,
                'user': order.user.username,
                'total_price': str(order.total_price),
                'status': order.status,
                'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                'details': details
            }
        })

    elif request.method == 'PUT':
        try:
            status = request.POST.get('status')
            if status:
                order.status = status
                order.save()

            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'id': order.id,
                    'status': order.status
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })


# 库存管理接口
@csrf_exempt
def update_stock(request, pk):
    if request.method == 'POST':
        try:
            product = Product.objects.get(pk=pk)
            quantity = int(request.POST.get('quantity', 0))
            operation = request.POST.get('operation')  # 'add' 或 'subtract'

            if operation == 'add':
                product.stock += quantity
            elif operation == 'subtract':
                if product.stock < quantity:
                    return JsonResponse({
                        'code': 400,
                        'message': '库存不足'
                    })
                product.stock -= quantity

            product.save()

            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'id': product.id,
                    'name': product.name,
                    'stock': product.stock
                }
            })
        except Product.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '商品不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })


# 统计分析接口
@csrf_exempt
def sales_statistics(request):
    try:
        # 获取时间范围
        days = int(request.GET.get('days', 7))
        end_date = timezone.now()
        start_date = end_date - timedelta(days=days)

        # 按日期统计销售额
        orders = Order.objects.filter(
            created_at__range=(start_date, end_date),
            status='Completed'
        )

        daily_sales = {}
        for order in orders:
            date = order.created_at.date()
            if date not in daily_sales:
                daily_sales[date] = 0
            daily_sales[date] += float(order.total_price)

        # 统计热销商品
        top_products = OrderDetail.objects.filter(
            order__created_at__range=(start_date, end_date),
            order__status='Completed'
        ).values('product__name').annotate(
            total_quantity=Sum('quantity'),
            total_sales=Sum('price_at_time_of_purchase')
        ).order_by('-total_quantity')[:5]

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'daily_sales': daily_sales,
                'top_products': list(top_products)
            }
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'获取失败: {str(e)}'
        })


@csrf_exempt
def data_overview(request):
    try:
        # 获取时间范围
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        if start_date and end_date:
            start_date = timezone.make_aware(datetime.strptime(start_date, '%Y-%m-%d'))
            end_date = timezone.make_aware(datetime.strptime(end_date, '%Y-%m-%d'))
        else:
            end_date = timezone.now()
            start_date = end_date - timedelta(days=30)

        # 计算上一个时间段
        time_diff = end_date - start_date
        prev_end_date = start_date
        prev_start_date = prev_end_date - time_diff

        # 获取当前时间段的数据
        current_orders = Order.objects.filter(created_at__range=(start_date, end_date))
        current_sales = current_orders.filter(status='Completed').aggregate(total=Sum('total_price'))['total'] or 0
        current_order_count = current_orders.count()
        current_product_count = Product.objects.filter(created_at__range=(start_date, end_date)).count()
        current_user_count = User.objects.filter(created_at__range=(start_date, end_date)).count()

        # 获取上一个时间段的数据
        prev_orders = Order.objects.filter(created_at__range=(prev_start_date, prev_end_date))
        prev_sales = prev_orders.filter(status='Completed').aggregate(total=Sum('total_price'))['total'] or 0
        prev_order_count = prev_orders.count()
        prev_product_count = Product.objects.filter(created_at__range=(prev_start_date, prev_end_date)).count()
        prev_user_count = User.objects.filter(created_at__range=(prev_start_date, prev_end_date)).count()

        # 计算环比变化
        def calculate_rate(current, previous):
            if previous == 0:
                return 100 if current > 0 else 0
            return ((current - previous) / previous) * 100

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'sales': {
                    'total': float(current_sales),
                    'rate': calculate_rate(current_sales, prev_sales)
                },
                'orders': {
                    'total': current_order_count,
                    'rate': calculate_rate(current_order_count, prev_order_count)
                },
                'products': {
                    'total': current_product_count,
                    'rate': calculate_rate(current_product_count, prev_product_count)
                },
                'users': {
                    'total': current_user_count,
                    'rate': calculate_rate(current_user_count, prev_user_count),
                    'list': list(User.objects.filter(created_at__range=(start_date, end_date)).values('id', 'username', 'email', 'created_at'))
                }
            }
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'获取失败: {str(e)}'
        })

@csrf_exempt
def sales_trend(request):
    try:
        # 获取时间范围和时间维度
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        time_dimension = request.GET.get('dimension', 'week')  # week, month, year

        if start_date and end_date:
            start_date = timezone.make_aware(datetime.strptime(start_date, '%Y-%m-%d'))
            end_date = timezone.make_aware(datetime.strptime(end_date, '%Y-%m-%d'))
        else:
            end_date = timezone.now()
            if time_dimension == 'week':
                start_date = end_date - timedelta(days=7)
            elif time_dimension == 'month':
                start_date = end_date - timedelta(days=30)
            else:  # year
                start_date = end_date - timedelta(days=365)

        # 准备数据结构
        trend_data = []
        current_date = start_date

        while current_date <= end_date:
            if time_dimension == 'week':
                next_date = current_date + timedelta(days=1)
                date_label = current_date.strftime('%Y-%m-%d')
            elif time_dimension == 'month':
                next_date = current_date + timedelta(days=30)
                date_label = current_date.strftime('%Y-%m')
            else:  # year
                next_date = current_date + timedelta(days=365)
                date_label = current_date.strftime('%Y')

            # 获取该时间段的订单数据
            period_orders = Order.objects.filter(
                created_at__range=(current_date, next_date),
                status='Completed'
            )
            sales_amount = period_orders.aggregate(total=Sum('total_price'))['total'] or 0
            order_count = period_orders.count()

            trend_data.append({
                'date': date_label,
                'sales': float(sales_amount),
                'orders': order_count
            })

            current_date = next_date

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': trend_data
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'获取失败: {str(e)}'
        })

@csrf_exempt
def product_statistics(request):
    try:
        # 获取时间范围
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        if start_date and end_date:
            start_date = timezone.make_aware(datetime.strptime(start_date, '%Y-%m-%d'))
            end_date = timezone.make_aware(datetime.strptime(end_date, '%Y-%m-%d'))
        else:
            end_date = timezone.now()
            start_date = end_date - timedelta(days=30)

        # 统计各分类商品数量及占比
        total_products = Product.objects.count()
        category_stats = Product.objects.values('category__name').annotate(
            count=Count('id'),
            total_stock=Sum('stock')
        ).order_by('-count')

        # 计算占比
        for stat in category_stats:
            stat['percentage'] = (stat['count'] / total_products * 100) if total_products > 0 else 0

        # 统计销售趋势数据
        sales_data = []
        orders_data = []
        dates = []
        current_date = start_date
        while current_date <= end_date:
            daily_orders = Order.objects.filter(
                created_at__date=current_date.date(),
                status='Completed'
            )
            daily_sales = daily_orders.aggregate(total=Sum('total_price'))['total'] or 0
            daily_order_count = daily_orders.count()
            
            dates.append(current_date.strftime('%Y-%m-%d'))
            sales_data.append(float(daily_sales))
            orders_data.append(daily_order_count)
            current_date += timedelta(days=1)
            
        # 获取热销商品TOP10
        hot_products = OrderDetail.objects.filter(
            order__created_at__range=(start_date, end_date),
            order__status='Completed'
        ).values('product__name', 'product__category__name').annotate(
            total_quantity=Sum('quantity'),
            total_sales=Sum('price_at_time_of_purchase')
        ).order_by('-total_quantity')[:10]

        # 转换热销商品数据格式
        hot_products_data = [{
            'name': product['product__name'],
            'category': product['product__category__name'],
            'quantity': product['total_quantity'],
            'sales': float(product['total_sales'])
        } for product in hot_products]

        # 统计订单状态分布
        order_status = Order.objects.filter(
            created_at__range=(start_date, end_date)
        ).values('status').annotate(
            count=Count('id')
        ).order_by('status')

        # 计算订单状态占比
        total_orders = sum(status['count'] for status in order_status)
        for status in order_status:
            status['percentage'] = (status['count'] / total_orders * 100) if total_orders > 0 else 0

        # 统计库存预警商品
        low_stock_threshold = 10  # 可以根据需求调整
        low_stock_products = Product.objects.filter(
            stock__lte=low_stock_threshold
        ).values('name', 'stock')

        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': {
                'category_stats': list(category_stats),
                'sales_trend': {
                    'dates': dates,
                    'sales': sales_data,
                    'orders': orders_data
                },
                'hot_products': hot_products_data,
                'order_status': list(order_status),
                'low_stock_products': list(low_stock_products)
            }
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'获取失败: {str(e)}'
        })


@csrf_exempt
def get_user_info(request):
    if request.method == 'GET':
        try:
            # 这里应该从session或token中获取用户ID
            # 暂时返回模拟数据
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'roles': ['admin'],
                    'introduction': 'I am a super administrator',
                    'avatar': 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
                    'name': 'Super Admin'
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取用户信息失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def reset_password(request):
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            phone = request.POST.get('phone')
            new_password = request.POST.get('new_password')
            confirm_password = request.POST.get('confirm_password')

            # print(username, phone, new_password, confirm_password)

            # 验证新密码和确认密码是否一致
            if new_password != confirm_password:
                return JsonResponse({
                    'code': 400,
                    'message': '新密码和确认密码不一致'
                })

            # 查找用户
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 验证手机号是否正确
            if user.phone_number != phone:
                return JsonResponse({
                    'code': 400,
                    'message': '手机号不正确'
                })

            # 更新密码
            user.password_hash = make_password(new_password)
            user.save()

            return JsonResponse({
                'code': 200,
                'message': '密码重置成功'
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'密码重置失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def update_user_state(request, user_id, mg_state):
    if request.method == 'PUT':
        try:
            user = User.objects.get(id=user_id)
            user.mg_state = mg_state.lower() == 'true'
            user.save()
            return JsonResponse({
                'code': 200,
                'message': '用户状态更新成功',
                'data': {
                    'user_id': user.id,
                    'mg_state': user.mg_state
                }
            })
        except User.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '用户不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新用户状态失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def add_user(request):
    if request.method == 'POST':
        try:
            username = request.POST.get('username')
            password = request.POST.get('password')
            email = request.POST.get('email', '')  # 邮箱是非必填项
            phone_number = request.POST.get('phone_number')
            # print("username",username,"password", password,"email:", email, "手机",phone_number)
            # 验证用户名是否已存在
            if User.objects.filter(username=username).exists():
                return JsonResponse({
                    'code': 400,
                    'message': '用户名已存在'
                })

            # 创建新用户
            user = User.objects.create(
                username=username,
                password_hash=make_password(password),
                email=email,
                phone_number=phone_number
            )

            return JsonResponse({
                'code': 200,
                'message': '用户添加成功',
                'data': {
                    'user_id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phone_number': user.phone_number
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'用户添加失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def update_user(request, user_id):
    if request.method == 'PUT':
        try:
            # 解析请求体中的 JSON 数据
            import json
            data = json.loads(request.body)

            # 获取用户对象
            user = User.objects.get(id=user_id)

            # 更新用户信息
            user.email = data.get('email', user.email)
            user.phone_number = data.get('phone_number', user.phone_number)

            # 保存更新
            user.save()

            return JsonResponse({
                'code': 200,
                'message': '用户信息更新成功',
                'data': {
                    'user_id': user.id,
                    'email': user.email,
                    'phone_number': user.phone_number
                },
            })
        except User.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '用户不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新用户信息失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def add_role(request):
    if request.method == 'POST':
        try:
            # 获取请求参数
            name = request.POST.get('name')
            description = request.POST.get('description', '')  # 描述是可选的
            # print("name",name, "desc:",description)

            # 验证角色名称是否已存在
            if Role.objects.filter(name=name).exists():
                return JsonResponse({
                    'code': 400,
                    'message': '角色名称已存在'
                })

            # 创建新角色
            role = Role.objects.create(
                name=name,
                description=description
            )

            return JsonResponse({
                'code': 200,
                'message': '角色添加成功',
                'data': {
                    'id': role.id,
                    'name': role.name,
                    'description': role.description
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'角色添加失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


# views.py
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Sum, Count
from decimal import Decimal
from datetime import timedelta
from django.utils import timezone
from .models import Product, User, Category, Order, OrderDetail, Role, Permission, CategoryHead, CategoryHeadChild
from rest_framework_simplejwt.tokens import RefreshToken
from django.shortcuts import get_object_or_404

@csrf_exempt
def get_category_products(request):
    if request.method == 'GET':
        try:
            # 获取分类ID
            category_id = request.GET.get('id')
            print(f"接收到的分类ID: {category_id}")
            if not category_id:
                return JsonResponse({
                    'code': 400,
                    'message': '分类ID不能为空'
                })

            # 检查分类是否存在
            try:
                category = Category.objects.get(id=category_id)
                print(f"找到分类: {category.name}")
            except Category.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': f'分类ID {category_id} 不存在'
                })
            except ValueError:
                return JsonResponse({
                    'code': 400,
                    'message': f'无效的分类ID格式: {category_id}'
                })

            # 获取该分类下的所有商品
            products = Product.objects.filter(category_id=category_id, status='published')
            print(f"查询到的商品数量: {products.count()}")
            
            # 如果没有找到商品，返回详细信息
            if not products.exists():
                return JsonResponse({
                    'code': 200,
                    'message': f'分类 {category.name} 下暂无已发布的商品',
                    'data': []
                })
            
            # 转换为列表格式
            result = [{
                'id': str(product.id),
                'name': product.name,
                'picture': f'/{product.image.name}' if product.image else None,
                'price': float(product.price),
                'description': product.description,
                'stock': product.stock,
                'category': product.category.name,
                'created_at': product.created_at.strftime('%Y-%m-%d %H:%M:%S')
            } for product in products]
            
            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': result
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取分类商品失败: {str(e)}'
            })
    
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def add_category(request):
    if request.method == 'POST':
        try:
            # 获取请求参数
            name = request.POST.get('name')
            parent_category_id = request.POST.get('parent_category_id')
            description = request.POST.get('description', '')
            status = request.POST.get('status', 'enabled')

            # 创建分类对象
            category = Category.objects.create(
                name=name,
                parent_category_id=parent_category_id if parent_category_id else None,
                description=description,
                status=status
            )

            return JsonResponse({
                'code': 200,
                'message': '分类添加成功',
                'data': {
                    'id': category.id,
                    'name': category.name,
                    'parent_category_id': category.parent_category_id,
                    'description': category.description,
                    'status': category.status
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'分类添加失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def edit_category(request, category_id):
    if request.method == 'PUT':
        try:
            # 获取要编辑的分类对象
            category = Category.objects.get(id=category_id)

            # 解析请求体中的 JSON 数据
            import json
            data = json.loads(request.body)

            # 更新分类信息
            category.name = data.get('name', category.name)
            category.description = data.get('description', category.description)
            category.status = data.get('status', category.status)
            parent_category_id = data.get('parent_category_id')
            if parent_category_id is not None:
                category.parent_category = Category.objects.get(id=parent_category_id) if parent_category_id else None

            # 保存更新
            category.save()

            return JsonResponse({
                'code': 200,
                'message': '分类更新成功',
                'data': {
                    'id': category.id,
                    'name': category.name,
                    'description': category.description,
                    'status': category.status,
                    'parent_category_id': category.parent_category.id if category.parent_category else None
                }
            })
        except Category.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '分类不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'分类更新失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def assign_role_functions(request):
    if request.method == 'POST':
        try:
            # 获取请求体中的 JSON 数据
            import json
            data = json.loads(request.body)
            role_name = data.get('role_name')
            user_id = data.get('user_id')
            print("data:",data)
            print("role_name:", role_name)
            print("user_id:", user_id)

            # 获取角色对象
            role = get_object_or_404(Role, name=role_name)
            print("role:", role)
            # 获取用户对象
            user = get_object_or_404(User, id=user_id)
            print("user:", user)
            # 将角色的功能分配给用户
            user.permissions.set(role.permissions.all())
            # 更新用户的角色描述信息
            user.role_description = role_name
            user.save()

            return JsonResponse({
                'code': 200,
                'message': '角色功能分配成功',
                'data': {
                    'user_id': user.id,
                    'username': user.username,
                    'role_name': role.name,
                    'functions': role.functions,
                    'role_description': user.role_description
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'角色功能分配失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def role_rights(request, role_id):
    if request.method == 'PUT':
        try:
            # 获取请求体中的 JSON 数据
            import json
            data = json.loads(request.body)
            print("data:", data)
            rights_map = json.loads(data.get('rightsMap', '{}'))  # 解析 rightsMap 字段
            print("rights_map:", rights_map)  # 确保输出格式正确

            # 获取角色对象
            role = get_object_or_404(Role, id=role_id)

            # 提取三位数的权限功能名称
            functions = []
            for key, value in rights_map.items():
                if len(key) == 3:  # 判断是否为三位数的权限ID
                    functions.append(value)

            # 将功能名称拼接成字符串
            functions_str = ', '.join(functions)

            # 更新角色的功能字段
            role.functions = functions_str if functions_str else None  # 确保 functions 不为空字符串
            role.save()

            return JsonResponse({
                'code': 200,
                'message': '权限分配成功',
                'data': {
                    'role_id': role.id,
                    'functions': role.functions
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'权限分配失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def get_role_functions(request, role_id):
    if request.method == 'GET':
        try:
            # 获取角色对象
            role = get_object_or_404(Role, id=role_id)
            print("role:", role)

            # 获取角色的功能字段，并将其转换为数组
            functions = role.functions.split(', ') if role.functions else []
            print("functions:", functions)
            return JsonResponse({
                'code': 200,
                'message': '获取角色功能成功',
                'data': {
                    'role_id': role.id,
                    'functions': functions
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取角色功能失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def get_all_role_functions(request):
    if request.method == 'GET':
        try:
            # 获取所有角色及其功能
            roles = Role.objects.all()
            roles_data = []
            for role in roles:
                functions = role.functions.split(', ') if role.functions else []
                roles_data.append({
                    'role_id': role.id,
                    'role_name': role.name,
                    'functions': functions
                })

            return JsonResponse({
                'code': 200,
                'message': '获取所有角色功能成功',
                'data': roles_data
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取所有角色功能失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def delete_cart_items(request):
    if request.method == 'DELETE':
        try:
            data = json.loads(request.body)
            ids = data.get('ids', [])
            clear_all = data.get('clearAll', False)
            clear_invalid = data.get('clearInvalid', False)

            # 获取用户的购物车项
            cart_items = CartItem.objects.filter(user_id=request.user.id)

            # 清空购物车
            if clear_all:
                cart_items.delete()
                return JsonResponse({'message': '购物车已清空'})

            # 清空无效商品
            if clear_invalid:
                invalid_items = cart_items.filter(product__stock=0)
                invalid_items.delete()
                return JsonResponse({'message': '无效商品已清空'})

            # 删除指定商品
            if ids:
                cart_items.filter(product_id__in=ids).delete()
                return JsonResponse({'message': '删除成功'})

            return JsonResponse({'message': '操作成功'})

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'服务器错误: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def add_to_cart(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            sku_id = data.get('skuId')
            count = data.get('count')

            # 验证参数
            if not sku_id or not count:
                return JsonResponse({
                    'code': 400,
                    'message': '参数错误'
                })

            # 获取商品信息
            try:
                product = Product.objects.get(id=sku_id)
            except Product.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '商品不存在'
                })

            # 验证库存
            if product.stock < count:
                return JsonResponse({
                    'code': 400,
                    'message': '库存不足'
                })

            # 获取或创建购物车项
            cart_item, created = CartItem.objects.get_or_create(
                user_id=request.user.id,
                product=product,
                defaults={'count': count}
            )

            # 如果购物车项已存在，更新数量
            if not created:
                cart_item.count = count
                cart_item.save()

            # 构建响应数据
            response_data = {
                'skuId': str(product.id),
                'name': product.name,
                'attrsText': product.description,
                'picture': request.build_absolute_uri(product.image.url) if product.image else '',
                'price': str(product.price),
                'nowPrice': str(product.price),  # 可以根据实际需求设置折扣价
                'selected': cart_item.selected,
                'stock': product.stock,
                'count': cart_item.count,
                'discount': 1,  # 可以根据实际需求设置折扣信息
                'isCollect': False,  # 可以根据实际需求设置收藏状态
                'isEffective': True,
                'id': str(product.id)
            }

            return JsonResponse({
                'message': '添加成功',
                'result': response_data
            })

        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的请求数据'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'服务器错误: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def create_address(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            print("前端传递过来的地址:", data)
            required_fields = ['receiver', 'contact', 'provinceCode', 'cityCode', 'address']
            missing_fields = [field for field in required_fields if field not in data or not data[field]]
            
            if missing_fields:
                return JsonResponse({
                    'code': 400,
                    'message': f'缺少必填字段: {', '.join(missing_fields)}'
                })
            
            # 验证用户是否存在
            try:
                user = User.objects.get(id=request.headers.get('x-user-id'))
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })
            
            # 验证邮编格式（如果提供）
            if data.get('postalCode') and not re.match(r'^[1-9]\d{5}$', str(data['postalCode'])):
                return JsonResponse({
                    'code': 400,
                    'message': '邮编格式不正确，请输入6位数字'
                })
            
            # 处理直辖市的特殊情况
            direct_administered_cities = ['北京市', '上海市', '天津市', '重庆市']
            if data['provinceCode'] in direct_administered_cities:
                # 对于直辖市，cityCode作为区级单位
                data['countyCode'] = data['cityCode']
                data['cityCode'] = data['provinceCode']
            elif not data.get('countyCode'):
                return JsonResponse({
                    'code': 400,
                    'message': '请选择完整的省市区信息'
                })
            
            # 如果设置为默认地址，先将其他地址设置为非默认
            if data.get('isDefault'):
                Address.objects.filter(user=user).update(is_default=False)
            
            # 创建新地址
            address = Address.objects.create(
                user=user,
                receiver=data['receiver'],
                phone=data['contact'],
                province_code=data['provinceCode'],
                city_code=data['cityCode'],
                county_code=data.get('countyCode', ''),
                detail=data['address'],
                postal_code=data.get('postalCode', ''),
                tags=data.get('addressTags', ''),
                is_default=bool(data.get('isDefault', 0))
            )
            
            # 构建返回数据
            result = {
                'id': str(address.id),
                'receiver': address.receiver,
                'contact': address.phone,
                'provinceCode': address.province_code,
                'cityCode': address.city_code,
                'countyCode': address.county_code,
                'address': address.detail,
                'postalCode': address.postal_code or '',
                'addressTags': address.tags or '',
                'isDefault': 1 if address.is_default else 0
            }
            
            return JsonResponse({
                'code': 200,
                'message': '操作成功',
                'result': result
            })
        except json.JSONDecodeError:
            return JsonResponse({
                'code': 400,
                'message': '无效的JSON数据'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'创建地址失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def address_operations(request):
    if request.method == 'GET':
        # 获取地址列表逻辑
        return get_address_list(request)
    elif request.method == 'POST':
        # 创建地址逻辑
        return create_address(request)
    else:
        return JsonResponse({'code': 405, 'message': '方法不允许'})

@csrf_exempt
def address_detail_operations(request, id):
    if request.method == 'PUT':
        # 更新地址逻辑
        return update_address(request, id)
    elif request.method == 'DELETE':
        # 删除地址逻辑
        return delete_address(request, id)
    else:
        return JsonResponse({'code': 405, 'message': '方法不允许'})

@csrf_exempt
def rights_list(request):
    if request.method == 'GET':
        # 模拟权限数据
        rights_data = [
            {
                'id': 1,
                'authName': '商品管理',
                'pid': 0,
                'path': '/api/products/',
                'level': 0,
                'children': [
                    {
                        'id': 11,
                        'authName': '商品列表',
                        'pid': 1,
                        'path': '/api/products/',
                        'level': 1,
                        'children': [
                            {'id': 111, 'authName': '添加商品', 'pid': 11, 'path': '/api/products/', 'level': 2},
                            {'id': 112, 'authName': '商品修改', 'pid': 11, 'path': '/api/products/', 'level': 2},
                            {'id': 113, 'authName': '商品删除', 'pid': 11, 'path': '/api/products/', 'level': 2},
                            {'id': 114, 'authName': '更新商品图片', 'pid': 11, 'path': '/api/products/', 'level': 2},
                            {'id': 115, 'authName': '更新商品属性', 'pid': 11, 'path': '/api/products/', 'level': 2},
                            {'id': 116, 'authName': '更新商品状态', 'pid': 11, 'path': '/api/products/', 'level': 2},
                            {'id': 117, 'authName': '获取商品详情', 'pid': 11, 'path': '/api/products/', 'level': 2}
                        ]
                    },
                    {
                        'id': 12,
                        'authName': '分类参数',
                        'pid': 1,
                        'path': '/api/category_params/',
                        'level': 1,
                        'children': [
                            {'id': 121, 'authName': '获取参数列表', 'pid': 12, 'path': '/api/category_params/', 'level': 2},
                            {'id': 122, 'authName': '创建商品参数', 'pid': 12, 'path': '/api/category_params/', 'level': 2},
                            {'id': 123, 'authName': '删除商品参数', 'pid': 12, 'path': '/api/category_params/', 'level': 2}
                        ]
                    },
                    {
                        'id': 13,
                        'authName': '商品分类',
                        'pid': 1,
                        'path': '/api/categories/',
                        'level': 1,
                        'children': [
                            {'id': 131, 'authName': '添加分类', 'pid': 13, 'path': '/api/categories/', 'level': 2},
                            {'id': 132, 'authName': '删除分类', 'pid': 13, 'path': '/api/categories/', 'level': 2},
                            {'id': 133, 'authName': '获取分类详情', 'pid': 13, 'path': '/api/categories/', 'level': 2}
                        ]
                    }
                ]
            },
            {
                'id': 2,
                'authName': '订单管理',
                'pid': 0,
                'path': '/api/orders/',
                'level': 0,
                'children': [
                    {
                        'id': 21,
                        'authName': '订单列表',
                        'pid': 2,
                        'path': '/api/orders/',
                        'level': 1,
                        'children': [
                            {'id': 211, 'authName': '添加订单', 'pid': 21, 'path': '/api/orders/', 'level': 2},
                            {'id': 212, 'authName': '订单更新', 'pid': 21, 'path': '/api/orders/', 'level': 2},
                            {'id': 213, 'authName': '获取订单详情', 'pid': 21, 'path': '/api/orders/', 'level': 2}
                        ]
                    }
                ]
            },
            {
                'id': 3,
                'authName': '权限管理',
                'pid': 0,
                'path': '/api/roles/',
                'level': 0,
                'children': [
                    {
                        'id': 31,
                        'authName': '角色列表',
                        'pid': 3,
                        'path': '/api/roles/',
                        'level': 1,
                        'children': [
                            {'id': 311, 'authName': '添加角色', 'pid': 31, 'path': '/api/roles/', 'level': 2},
                            {'id': 312, 'authName': '删除角色', 'pid': 31, 'path': '/api/roles/', 'level': 2},
                            {'id': 313, 'authName': '角色授权', 'pid': 31, 'path': '/api/roles/', 'level': 2},
                            {'id': 314, 'authName': '取消角色授权', 'pid': 31, 'path': '/api/roles/', 'level': 2},
                            {'id': 315, 'authName': '获取角色列表', 'pid': 31, 'path': '/api/roles/', 'level': 2},
                            {'id': 316, 'authName': '获取角色详情', 'pid': 31, 'path': '/api/roles/', 'level': 2},
                            {'id': 317, 'authName': '更新角色信息', 'pid': 31, 'path': '/api/roles/', 'level': 2}
                        ]
                    },
                    {
                        'id': 32,
                        'authName': '权限列表',
                        'pid': 3,
                        'path': '/api/permissions/',
                        'level': 1,
                        'children': [
                            {'id': 321, 'authName': '查看权限', 'pid': 32, 'path': '/api/permissions/', 'level': 2}
                        ]
                    }
                ]
            },
            {
                'id': 4,
                'authName': '用户管理',
                'pid': 0,
                'path': '/user/list/',
                'level': 0,
                'children': [
                    {
                        'id': 41,
                        'authName': '用户列表',
                        'pid': 4,
                        'path': '/user/list/',
                        'level': 1,
                        'children': [
                            {'id': 411, 'authName': '添加用户', 'pid': 41, 'path': '/user/list/', 'level': 2},
                            {'id': 412, 'authName': '删除用户', 'pid': 41, 'path': '/user/list/', 'level': 2},
                            {'id': 413, 'authName': '更改用户', 'pid': 41, 'path': '/user/list/', 'level': 2},
                            {'id': 414, 'authName': '获取用户详情', 'pid': 41, 'path': '/user/list/', 'level': 2},
                            {'id': 415, 'authName': '分配用户角色', 'pid': 41, 'path': '/user/list/', 'level': 2},
                            {'id': 416, 'authName': '设置管理状态', 'pid': 41, 'path': '/user/list/', 'level': 2}
                        ]
                    }
                ]
            },
            {
                'id': 5,
                'authName': '数据统计',
                'pid': 0,
                'path': '/api/statistics/',
                'level': 0,
                'children': [
                    {
                        'id': 51,
                        'authName': '数据报表',
                        'pid': 5,
                        'path': '/api/statistics/',
                        'level': 1,
                        'children': [
                            {'id': 511, 'authName': '查看数据', 'pid': 51, 'path': '/api/statistics/', 'level': 2}
                        ]
                    }
                ]
            }
        ]
        return JsonResponse({
            'code': 200,
            'message': '获取成功',
            'data': rights_data
        })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


@csrf_exempt
def delete_user(request, user_id):
    if request.method == 'DELETE':
        try:
            user = User.objects.get(id=user_id)
            user.delete()
            return JsonResponse({
                'code': 200,
                'message': '用户删除成功'
            })
        except User.DoesNotExist:
            return JsonResponse({
                'code': 404,
                'message': '用户不存在'
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'删除用户失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })
@csrf_exempt
def delete_role_right(request, role_id, right_name):
    if request.method == 'DELETE':
        try:
            # 获取角色对象
            role = get_object_or_404(Role, id=role_id)

            # 获取角色的功能字段，并将其转换为数组
            functions = role.functions.split(', ') if role.functions else []

            # 删除指定的权限功能
            if right_name in functions:
                functions.remove(right_name)
                role.functions = ', '.join(functions) if functions else None
                role.save()

                return JsonResponse({
                    'code': 200,
                    'message': '权限删除成功',
                    'data': {
                        'role_id': role.id,
                        'functions': functions
                    }
                })
            else:
                return JsonResponse({
                    'code': 404,
                    'message': '权限功能不存在'
                })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'权限删除失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })



from django.shortcuts import render
from django.http import JsonResponse
from .models import Role, Permission
from .serializers import RoleSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@csrf_exempt
def role_list(request):
    if request.method == 'GET':
        try:
            # 获取所有角色
            roles = Role.objects.all()
            roles_list = list(roles.values('id', 'name', 'description', 'functions'))
            return JsonResponse({
                'code': 200,
                'message': '获取角色列表成功',
                'data': roles_list
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取角色列表失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@api_view(['GET', 'POST'])
def role_list_create(request):
    if request.method == 'GET':
        roles = Role.objects.all()
        serializer = RoleSerializer(roles, many=True)
        return Response({
            'code': 200,
            'message': '获取角色列表成功',
            'data': serializer.data
        })

    elif request.method == 'POST':
        serializer = RoleSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 201,
                'message': '角色创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        return Response({
            'code': 400,
            'message': '角色创建失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET', 'PUT', 'DELETE'])
def role_detail(request, pk):
    try:
        role = Role.objects.get(pk=pk)
    except Role.DoesNotExist:
        return Response({
            'code': 404,
            'message': '角色不存在'
        }, status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = RoleSerializer(role)
        return Response({
            'code': 200,
            'message': '获取角色详情成功',
            'data': serializer.data
        })

    elif request.method == 'PUT':
        serializer = RoleSerializer(role, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '角色更新成功',
                'data': serializer.data
            })
        return Response({
            'code': 400,
            'message': '角色更新失败',
            'errors': serializer.errors
        }, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        role.delete()
        return Response({
            'code': 204,
            'message': '角色删除成功'
        }, status=status.HTTP_204_NO_CONTENT)


from django.http import JsonResponse


def role_expand(request):
    # 检查请求方法是否为GET
    if request.method == 'GET':
        # 定义角色扩展信息的数据结构
        role_data = [
            {
                "id": 1, "authName": "商品管理", "children": [
                {"id": 11, "authName": "商品列表", "children": [
                    {"id": 111, "authName": "添加商品"},
                    {"id": 112, "authName": "商品修改"},
                    {"id": 113, "authName": "商品删除"},
                    {"id": 114, "authName": "更新商品图片"},
                    {"id": 115, "authName": "更新商品属性"},
                    {"id": 116, "authName": "更新商品状态"},
                    {"id": 117, "authName": "获取商品详情"}
                ]},
                # {"id": 12, "authName": "分类参数", "children": [
                #     {"id": 121, "authName": "获取参数列表"},
                #     {"id": 122, "authName": "创建商品参数"},
                #     {"id": 123, "authName": "删除商品参数"}
                # ]},
                {"id": 13, "authName": "商品分类", "children": [
                    {"id": 131, "authName": "添加分类"},
                    {"id": 132, "authName": "删除分类"},
                    {"id": 133, "authName": "获取分类详情"}
                ]}
            ]
            },
            {
                "id": 2, "authName": "订单管理", "children": [
                {"id": 21, "authName": "订单列表", "children": [
                    {"id": 211, "authName": "添加订单"},
                    {"id": 212, "authName": "订单更新"},
                    {"id": 213, "authName": "获取订单详情"}
                ]}
            ]
            },
            {
                "id": 3, "authName": "权限管理", "children": [
                {"id": 31, "authName": "角色列表", "children": [
                    {"id": 311, "authName": "添加角色"},
                    {"id": 312, "authName": "删除角色"},
                    {"id": 313, "authName": "角色授权"},
                    {"id": 314, "authName": "取消角色授权"},
                    {"id": 315, "authName": "获取角色列表"},
                    {"id": 316, "authName": "获取角色详情"},
                    {"id": 317, "authName": "更新角色信息"}
                ]},
                # {"id": 32, "authName": "权限列表", "children": [
                #     {"id": 321, "authName": "查看权限"}
                # ]}
            ]
            },
            {
                "id": 4, "authName": "用户管理", "children": [
                {"id": 41, "authName": "用户列表", "children": [
                    {"id": 411, "authName": "添加用户"},
                    {"id": 412, "authName": "删除用户"},
                    {"id": 413, "authName": "更改用户"},
                    {"id": 414, "authName": "获取用户详情"},
                    {"id": 415, "authName": "分配用户角色"},
                    {"id": 416, "authName": "设置管理状态"}
                ]}
            ]
            },
            {
                "id": 5, "authName": "数据统计", "children": [
                {"id": 51, "authName": "数据报表", "children": [
                    {"id": 511, "authName": "查看数据"}
                ]}
            ]
            }
        ]

        # 返回JSON响应
        return JsonResponse(role_data, safe=False)

    # 如果不是GET请求，则返回方法不允许的状态码
    else:
        return JsonResponse({"code": 405, "message": "Method Not Allowed"}, status=405)

@csrf_exempt
def all_products(request):
    if request.method == 'GET':
        try:
            # 获取分页参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            # 添加: 获取搜索关键字参数
            search = request.GET.get('query', '')
            # 添加: 获取分类参数
            category = request.GET.get('category_query', '')

            # 获取所有商品
            products = Product.objects.all()
            # 添加: 根据搜索关键字过滤商品
            if search:
                products = products.filter(name__icontains=search)
            # 添加: 根据分类名称过滤商品
            if category:
                products = products.filter(category__name__icontains=category)

            # 计算分页数据
            start = (page - 1) * page_size
            end = start + page_size
            paginated_products = products[start:end]

            # 转换为列表
            products_list = list(paginated_products.values('id', 'name', 'description', 'price', 'stock', 'category__name', 'image', 'status', 'created_at', 'updated_at'))

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': products_list,
                'total': products.count(),
                'page': page,
                'page_size': page_size
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取商品失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

import os
@csrf_exempt
def upload_image(request):
    if request.method == 'POST':
        try:
            image = request.FILES.get('image')
            if not image:
                return JsonResponse({
                    'code': 400,
                    'message': '没有上传图片'
                })

            # 生成文件路径
            file_path = os.path.join(settings.MEDIA_ROOT, 'products', image.name)
            # 保存文件
            default_storage.save(file_path, image)  # 确保此处使用正确的存储对象

            return JsonResponse({
                'code': 200,
                'message': '图片上传成功',
                'data': {
                    'url': os.path.join(settings.MEDIA_URL, 'products', image.name)
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'图片上传失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def update_product(request, pk):
    if request.method == 'PUT' or request.method == 'POST':  # 同时支持PUT和POST请求
        try:
            # 获取商品对象
            try:
                product = Product.objects.get(pk=pk)
            except Product.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '商品不存在'
                })

            # 处理表单数据和文件上传
            if request.content_type and 'multipart/form-data' in request.content_type:
                # 处理表单数据
                name = request.POST.get('name')
                description = request.POST.get('description')
                price = request.POST.get('price')
                stock = request.POST.get('stock')
                category_id = request.POST.get('category_id')
                image = request.FILES.get('image')  # 获取上传的图片文件
                
                # 打印从表单中获取的数据
                print("从表单中获取的数据：")
                print(f"name: {name}")
                print(f"description: {description}")
                print(f"price: {price}")
                print(f"stock: {stock}")
                print(f"category_id: {category_id}")
                print(f"image: {image}")
                
                # 更新商品信息
                if name:
                    product.name = name
                if description:
                    product.description = description
                if price:
                    product.price = Decimal(price)
                if stock:
                    product.stock = int(stock)
                if category_id:
                    product.category_id = category_id
                if image:
                    product.image = image
            else:
                # 解析JSON数据
                import json
                data = json.loads(request.body)
                
                # 打印从请求体中获取的数据
                print("从请求体中获取的数据：")
                print(f"name: {data.get('name')}")
                print(f"description: {data.get('description')}")
                print(f"price: {data.get('price')}")
                print(f"stock: {data.get('stock')}")
                print(f"category_id: {data.get('category_id')}")
                print(f"image: {data.get('image')}")
                
                # 更新商品信息
                product.name = data.get('name', product.name)
                product.description = data.get('description', product.description)
                if 'price' in data:
                    product.price = Decimal(data.get('price'))
                if 'stock' in data:
                    product.stock = int(data.get('stock'))
                if 'category_id' in data:
                    product.category_id = data.get('category_id')
                if 'image' in data:
                    product.image = data.get('image')

            # 保存更新
            product.save()

            return JsonResponse({
                'code': 200,
                'message': '更新成功',
                'data': {
                    'id': product.id,
                    'name': product.name,
                    'price': str(product.price),
                    'stock': product.stock,
                    'image': product.image.url if product.image else None
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def order_list(request):
    if request.method == 'GET':
        try:
            # 获取分页参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 8))
            # 获取搜索关键字参数
            search = request.GET.get('query', '')  # 前端传递的搜索参数名为 query
            # 获取订单状态参数
            status = request.GET.get('status', '')

            # 获取所有订单
            orders = Order.objects.all().order_by('-created_at')  # 按创建时间倒序排列
            
            # 根据搜索关键字过滤订单（用户名或订单ID）
            if search:
                # 构建订单号格式
                order_number_pattern = f'ORDER{search}'
                # 使用Q对象组合多个搜索条件
                from django.db.models import Q
                orders = orders.filter(
                    Q(user__username__icontains=search) |  # 用户名模糊搜索
                    Q(id__icontains=search)  # 订单ID模糊搜索
                )
            
            # 根据订单状态过滤订单
            if status:
                orders = orders.filter(status=status)

            # 获取总记录数
            total = orders.count()
            
            # 计算分页数据
            start = (page - 1) * page_size
            end = start + page_size
            paginated_orders = orders[start:end]

            # 构建订单列表
            orders_list = []
            for order in paginated_orders:
                # 获取订单详情
                order_details = OrderDetail.objects.filter(order=order)
                details = []
                for detail in order_details:
                    details.append({
                        'id': detail.id,
                        'product_id': detail.product.id,
                        'product_name': detail.product.name,
                        'quantity': detail.quantity,
                        'price': str(detail.price_at_time_of_purchase),
                        'total_price': str(detail.quantity * detail.price_at_time_of_purchase),
                    })

                # 构建订单数据
                orders_list.append({
                    'id': order.id,
                    'order_number': f'ORDER{order.id:06d}',  # 生成订单号
                    'user_id': order.user.id,
                    'username': order.user.username,
                    'total_price': str(order.total_price),
                    'status': order.status,
                    'is_send': order.is_send,  # 添加发货状态
                    'consignee_addr': order.consignee_addr,  # 收货地址
                    'fapiao_title': order.fapiao_title,  # 发票抬头
                    'fapiao_company': order.fapiao_company,  # 发票公司
                    'fapiao_content': order.fapiao_content,  # 发票内容
                    'created_at': order.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    # 'updated_at': order.updated_at.strftime('%Y-%m-%d %H:%M:%S') if order.updated_at else None,
                    'details': details,
                    'address': order.address if hasattr(order, 'address') else None,
                    'phone': order.user.phone_number
                })

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'orders': orders_list
                }
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取订单列表失败: {str(e)}'
            })
            
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def update_address(request, id):
    if request.method == 'PUT':
        try:
            # 获取地址对象
            try:
                address = Address.objects.get(pk=id)
            except Address.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '地址不存在'
                })
            
            import json
            data = json.loads(request.body)
            
            # 验证必填字段
            required_fields = ['receiver', 'contact', 'provinceCode', 'cityCode', 'countyCode', 'address', 'addressTags', 'isDefault']
            for field in required_fields:
                if field not in data:
                    return JsonResponse({
                        'code': 400,
                        'message': f'缺少必填字段: {field}'
                    })
            
            # 更新地址信息
            address.receiver = data['receiver']
            address.contact = data['contact']
            address.provinceCode = data['provinceCode']
            address.cityCode = data['cityCode']
            address.countyCode = data['countyCode']
            address.address = data['address']
            address.postalCode = data['postalCode']
            address.addressTags = data['addressTags']
            
            # 处理默认地址逻辑
            if data['isDefault'] == 0:
                # 取消其他默认地址
                Address.objects.filter(user=address.user, isDefault=0).update(isDefault=1)
                address.isDefault = 0
            else:
                address.isDefault = 1
            
            address.save()
            
            return JsonResponse({
                'code': 200,
                'message': '地址更新成功',
                'data': {
                    'id': address.id,
                    'receiver': address.receiver,
                    'contact': address.contact
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新地址失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })

@csrf_exempt
def update_order_address(request, order_id):
    if request.method == 'PUT':
        try:
            # 获取订单对象
            try:
                order = Order.objects.get(pk=order_id)
            except Order.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '订单不存在'
                })
            import json
            # 解析请求数据
            data = json.loads(request.body)
            new_address = data.get('address')

            if not new_address:
                return JsonResponse({
                    'code': 400,
                    'message': '收货地址不能为空'
                })

            # 更新收货地址
            order.consignee_addr = new_address
            order.save()

            return JsonResponse({
                'code': 200,
                'message': '收货地址更新成功',
                'data': {
                    'order_id': order.id,
                    'order_number': f'ORDER{order.id:06d}',
                    'consignee_addr': order.consignee_addr
                }
            })

        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'更新收货地址失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


from .models import Category

@csrf_exempt
def category_tree(request):
    if request.method == 'GET':
        try:
            # 获取所有分类
            categories = Category.objects.filter(parent_category=None)

            # 递归函数来构建分类树
            def build_category_tree(category):
                children = Category.objects.filter(parent_category=category)
                category_data = {
                    'id': category.id,
                    'name': category.name,
                    'description': category.description,
                    'status': category.status,
                    'children': [build_category_tree(child) for child in children]
                }
                return category_data

            # 构建分类树
            category_tree_data = [build_category_tree(category) for category in categories]

            return JsonResponse({
                'code': 200,
                'message': '获取成功',
                'data': category_tree_data
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取分类树失败: {str(e)}'
            })
    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


from rest_framework_simplejwt.tokens import RefreshToken, TokenError


@csrf_exempt
def refresh_token(request):
    if request.method == 'PUT':
        try:
            # 获取请求头中的 Authorization 字段
            auth_header = request.headers.get('Authorization')
            if not auth_header or not auth_header.startswith('Bearer '):
                return JsonResponse({
                    'code': 400,
                    'message': '无效的Authorization头'
                })

            # 提取token
            token = auth_header.split(' ')[1]

            # 获取请求体中的用户信息
            data = json.loads(request.body)
            account = data.get('account')
            user_id = data.get('id')

            # 验证用户信息
            try:
                user = User.objects.get(Q(username=account) | Q(phone_number=account), id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 刷新token
            try:
                refresh = RefreshToken(token)
                new_access_token = str(refresh.access_token)
            except TokenError:
                return JsonResponse({
                    'code': 400,
                    'message': '无效的token'
                })

            return JsonResponse({
                'code': 200,
                'message': 'token刷新成功',
                'data': {
                    'token': new_access_token,
                    'user_id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'phone_number': user.phone_number
                }
            })
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'token刷新失败: {str(e)}'
            })

    return JsonResponse({
        'code': 405,
        'message': '方法不允许'
    })


